13
votes

Currently the Validator will fail if I have a required rule for a key "name", but I haven't passed it in the data array. I want it not to fail in this case. I want to validate only the fields which exist in the data array. Is there a builtin way for that to happen, or I have to extend the Validator class?

3
Why do you use required on an input value that is NOT required?chris342423

3 Answers

30
votes

You can use the sometimes validation rule.

In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list.

http://laravel.com/docs/validation#conditionally-adding-rules

$v = Validator::make($data, array(
    'email' => 'sometimes|required|email',
));

Be sure to run composer update since the sometimes shortcut is a Laravel 4.1.14 feature.

https://twitter.com/laravelphp/status/422463139293057024

14
votes

You can use nullable and it will pass if email is not present

$request->validate([
    'name' => 'required',
    'email' => 'nullable|email'
])

Also, you should remove required validation.

0
votes

For Laravel version less then 5.9

For anyone, having the validator object, using:

Method ->validateFilled(string $attribute, mixed $value)

may also help them to validate the given attribute is filled if it is present. May help someone in their respective case.

Source:- https://laravel.com/api/5.8/Illuminate/Validation/Validator.html#method_validateFilled