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.

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 68 courses (1188 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses