In Laravel 5, let's consider those 2 different validation rules:
Validator::make($data, ['email' => 'sometimes|email']);
and
Validator::make($data, ['email' => 'email']);
After testing it:
So what's the difference between those two rules? What's the purpose of "sometimes"?
From Laravel's validation docs:
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.
So, essentially, email
will only be validated if the field is actually part of the POST
request.
This is particularly useful with the required
rule, where the field will throw an error if left blank, but with sometimes
will only do so if the field exists in the first place. Without sometimes
, a missing physical field will always cause a "required field" error.
It's not something you'll need often, but it's a nifty little feature to have.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With