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:

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

Now, it sounds confusing at first, I know. 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.

Simple, but might be useful.

Like our articles?
Check out our Laravel online courses!

2 COMMENTS

  1. Wow this was SO incredibly useful. Been struggling with some tests for two days now. In the test case I only want to pass the ‘account_number’ field to see if the update works correctly, but in the request class I validate all the fields. Now my validation kept failing based on the values of other fields instead of the one I actually want to check. Sometimes you need to do a partial update and won’t be providing all the fields but you still want to use the same request class.

    This caters for that exact scenario. Thank you so much Povilas.

LEAVE A REPLY

Please enter your comment!
Please enter your name here