Laravel 验证器`required` 也因空字符串而失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28020637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:44:06  来源:igfitidea点击:

Laravel validator `required` fails for empty string also

phpmacosvalidationlaravel

提问by shahalpk

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

我正在required我的代码中尝试 laravel验证器,不幸的是它甚至对空字符串也失败了。我不希望它因空字符串而失败。

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

It gives me the following output

它给了我以下输出

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)

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

它应该通过,因为我给出了一个空字符串作为name字段。

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).

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

回答by lukasgeiter

The requiredrule actually returns false if you pass an empty string.

required如果您传递一个空字符串,该规则实际上会返回 false。

If we look at the code (Illuminate\Validation\Validator)

如果我们看代码 ( 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 rulethat checks if the value is not null:

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

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

(The extendImplicitis needed because with extendcustom rules will only run when the value is not an empty string)

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

And then use it like this:

然后像这样使用它:

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

回答by Igor Panchenko

I use this:

我用这个:

'my_field' => 'present'  

回答by iosifv

In Laravel 5.6 you can use just this:

在 Laravel 5.6 中你可以只使用这个:

public function rules()
{
    return [
        'my_field' => 'required|string|nullable'
    ];
}

Might work on older versions as well, I only tried on 5.6

可能也适用于旧版本,我只试过 5.6

回答by The EasyLearn Academy

i have developed my own way to process optional input. i use associative array for validation.

我开发了自己的方式来处理可选输入。我使用关联数组进行验证。

$rules = array('sltcategoryid' => 'required',   
            'txttitle' => 'required|min:10|max:255',    
            'txtdetail' => 'required|min:10|max:255',   
            'rdocontenttype' => 'required', 
            'rdoislive' => 'required');
         if($request->rdocontenttype=="1" || $request->rdocontenttype=="2" && trim($request->txtcontent)=="")
            $rules["txtcontent"]="required|min:10|max:2048";
         else if ($request->rdocontenttype=="3" && isset($request->fildata)==false)
             $rules["fildata"] ="required|mimes:png,jpg,jpeg,pdf,doc,xls,ppt,bmp,zip";
         $validator = Validator::make($request->all(),$rules);
         if ($validator->fails()) 
                return redirect('content/create')->withErrors($validator)->withInput();
             else 
                return back()->with("message","content processed successfully");