sha*_*lpk 7 php validation macos laravel
我正在尝试required在我的代码中使用laravel 验证器,不幸的是它甚至因空字符串而失败.我不希望它因空字符串而失败.
$validator = \Validator::make(array("name"=>""), array("name"=>"required"));
if ($validator->fails()){
var_dump($validator->messages());
} else {
die("no errors :)");
}
Run Code Online (Sandbox Code Playgroud)
它给了我以下输出
object(Illuminate\Support\MessageBag)[602]
protected 'messages' =>
array (size=1)
'name' =>
array (size=1)
0 => string 'The name field is required.' (length=27)
protected 'format' => string ':message' (length=8)
Run Code Online (Sandbox Code Playgroud)
它应该通过,因为我给了一个空字符串作为name字段.
上述行为发生在OSX环境(PHP版本5.5.18)中,但它在Linux环境中运行良好(PHP版本5.5.9-1ubuntu4.5).
luk*_*ter 11
的required,如果你传递一个空字符串规则实际上返回false.
如果我们看一下代码(Illuminate\Validation\Validator)
protected function validateRequired($attribute, $value)
{
if (is_null($value))
{
return false;
}
elseif (is_string($value) && trim($value) === '')
{
return false;
}
// [...]
return true;
}
Run Code Online (Sandbox Code Playgroud)
我认为你唯一的选择就是编写自己的验证规则来检查值是否为空:
Validator::extendImplicit('attribute_exists', function($attribute, $value, $parameters){
return ! is_null($value);
});
Run Code Online (Sandbox Code Playgroud)
(这extendImplicit是必需的,因为extend自定义规则只会在值不是空字符串时运行)
然后像这样使用它:
\Validator::make(array("name"=>""), array("name"=>"attribute_exists"));
Run Code Online (Sandbox Code Playgroud)
在 Laravel 5.6 中你可以只使用这个:
public function rules()
{
return [
'my_field' => 'required|string|nullable'
];
}
Run Code Online (Sandbox Code Playgroud)
可能也适用于旧版本,我只试过 5.6
| 归档时间: |
|
| 查看次数: |
11295 次 |
| 最近记录: |