Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 - real meaning of "sometimes" in validation rules

Tags:

php

laravel

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:

  • if $data['email'] exists and is a valid email => both will succeed.
  • if $data['email'] exists and is not a valid email => both will fail.
  • if $data does have an email key => both will succeed.

So what's the difference between those two rules? What's the purpose of "sometimes"?

like image 674
PGBI Avatar asked Oct 08 '15 23:10

PGBI


1 Answers

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.

like image 68
Stuart Wagner Avatar answered Oct 08 '22 09:10

Stuart Wagner