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 Answers
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.
-
-
why on earth I would set "sometimes" and "required"? If it's "sometimes required", its nullable. Am I wrong? May 3, 2018 at 14:58
-
1I guess you may want to check that if a field is present, has not to be empty, i think that case cover this Jul 20, 2018 at 9:31
-
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.
-
5This isn't correct though. Let's say you have a login form and make the email field nullable, it will allow you to send the form without having entered an email address. With
sometimes
you can also userequired
at the same time which is probably needed for something like a login form. Apr 24, 2019 at 8:18 -
Why on earth would you use sometimes and required? You have
required_with
,required_if
for conditional cases. Apr 24, 2019 at 17:48 -
I literally gave you an example. If somehow you're stubborn and still not convinced; the docs even tell you why to use it: "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". Apr 25, 2019 at 8:01
-
3I think this solution makes more sense because when you use sometimes, it will expect the field itself not present in the request, but in most cases, we do have the field present in the request but empty. Thanks again 🙏– StrangerJul 18, 2019 at 5:15
-
1It took me a few reads to get this. In case it helps someone else - the difference is in whether the field will always appear in the request but might have a null value, or might sometimes not appear in the request at all. Use
nullable
for the former, andsometimes
for the latter. There is a related note about this in the docs. Apr 22, 2021 at 12:38
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