本文介绍了Laravel验证器`required`也因空字符串而失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的代码中尝试使用laravel required验证程序,不幸的是,即使是空字符串,验证程序也会失败.我不希望它为空字符串失败.

I'm trying laravel required validator in my code, unfortunately it fails for even empty string. I do not want it fail for empty string.

$validator = \Validator::make(array("name"=>""), array("name"=>"required"));
if ($validator->fails()){
    var_dump($validator->messages());
} else {
    die("no errors :)");
}

它给了我以下输出

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)

应该通过,因为我在name字段中输入了一个空字符串.

It is supposed to pass, since i'm giving an empty string as the name field.

上述行为在OSX环境(PHP版本5.5.18)中发生,但在Linux环境(PHP版本5.5.9-1ubuntu4.5)中运行良好.

The above behavior happens in OSX environment (PHP Version 5.5.18), but it works fine in linux environment (PHP Version 5.5.9-1ubuntu4.5).

推荐答案

如果传递空字符串,required规则实际上返回false.

The required rule actually returns false if you pass an empty string.

如果我们看代码(Illuminate\Validation\Validator)

protected function validateRequired($attribute, $value)
{
    if (is_null($value))
    {
        return false;
    }
    elseif (is_string($value) && trim($value) === '')
    {
        return false;
    }

    // [...]

    return true;
}

我认为您唯一的选择是编写您的自己的验证规则检查该值是否不为空:

I think your only option here is to write your own validation rule that checks if the value is not null:

Validator::extendImplicit('attribute_exists', function($attribute, $value, $parameters){
    return ! is_null($value);
});

(extendImplicit是必需的,因为使用extend时,自定义规则仅在值不是空字符串时运行)

(The extendImplicit is needed because with extend custom rules will only run when the value is not an empty string)

然后像这样使用它:

\Validator::make(array("name"=>""), array("name"=>"attribute_exists"));

这篇关于Laravel验证器`required`也因空字符串而失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-11 15:36