Validation rule “sometimes”: apply rules only if field exists

Recently I’ve found out an interesting validation rule for form fields in Laravel, and I want to briefly tell you about it.

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

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

Now, it sounds confusing at first, I know. Let’s look at the difference between this code and the “simple” one:

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.

Simple, but might be useful.

Check out my new online course: Laravel Eloquent: Expert Level

Leave a Reply

Your email address will not be published. Required fields are marked *