Friday, May 20, 2016

Laravel 5 Validation rules "sometimes"

Hi

Today we will discuss validation rules "sometimes", apply rules only if field exists.

Imagine that we have two forms – one with username/password fields and another with email/password fields. And we want to have the same validation rules (either in Request, or directly in Controller, doesn’t matter).

And we need to validate if the email is filled in ONLY if that field is present within the form. Then we call it ‘sometimes’.

$this->validate($request, [
  'email' => 'sometimes|required|email'
]);

To understand better, Let’s look at the difference between this code and the “simple” one:

$this->validate($request, [
  'email' => 'required|email'
]);

The second validation will fail if the email field is empty or is not in the form at all. That’s the key point – the first validation will fail only when the field is present but empty.

It is simple but I hope that it will help someone.

Thanks

No comments:

Post a Comment