Home » Php » Laravel validator `required` fails for empty string also

Laravel validator `required` fails for empty string also

Posted by: admin November 30, 2017 Leave a comment

Questions:

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 :)");
}

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 name field.

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

Answers:

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

If we look at the code (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);
});

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

And then use it like this:

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