Laravel sometimes vs sometimes|required

17,497

From the 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

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

If I could simplify it, I would say sometimes means, only apply the rest of the validation rules if the field shows up in the request. Imagine sometimes is like an if statement that checks if the field is present in the request/input before applying any of the rules.

I use this rule when I have some javascript on a page that will disable a field, as when a field is disabled it won't show up in the request. If I simply said required|email the validator is always going to apply the rules whereas using the sometimes rule will only apply the validation if the field shows up in the request! Hope that makes sense.

Examples:

input: []
rules: ['email' => 'sometimes|required|email']
result: pass, the request is empty so sometimes won't apply any of the rules

input: ['email' => '']
rules: ['email' => 'sometimes|required|email']
result: fail, the field is present so the required rule fails!

input: []
rules: ['email' => 'required|email']
result: fail, the request is empty and we require the email field!
Share:
17,497
alex
Author by

alex

MSC in software engineering. interested in OWL ontology & semantic web

Updated on July 14, 2022

Comments

  • alex
    alex almost 2 years

    What is the difference between sometimes|required|email and sometimes|email in Laravel validation?I've read this discussion from laracasts but still it is ambiguous for me

  • alex
    alex about 8 years
    thanks. as i understand sometimes refers to POST key and require refers to its value.so if a field is required both key and value should be present in POST .am i right?
  • haakym
    haakym about 8 years
    You could actually apply the validation process to any old array actually and it could therefore be POST or GET. And yes, that's actually a good way of explaining it. You can of course combine the sometimes and required rule. If you want further details of how it works in the framework you can always check the source: github.com/laravel/framework/blob/5.2/src/Illuminate/Validat‌​ion/… and the tests: github.com/laravel/framework/blob/5.2/tests/Validation/…