Laravel Validation: 5 Less-known Rules

A short list in "Did you know...?" style. Laravel has a convenient validation mechanism, but most of us only use simple rules like 'required', 'email' or 'date'. Actually, there are a few less-known but pretty interesting ones. Let's have a look. First, let me remind you how it works. You can create an array of validation rules with one or more rules for every field. Like this:
[
  'title' => 'required|unique:posts|max:255',
  'body' => 'required',
];
And then you can use that array in a separate Form Request class or inside of your Controller, calling $this->validate() method. Now, let's see what rules are less used but may be useful.

1. accepted

The field under validation must be yes, on, 1, or true. This is useful for validating "Terms of Service" acceptance.

2. confirmed

Used mostly for repeating password, as a confirmation. The field under validation must have a matching field of [field]_confirmation.

3. dimensions:ratio

The file under validation must be an image meeting the dimension constraints as specified by the rule's parameters. Example for 3:2 images like 600x400 or 300x200:
'avatar' => 'dimensions:ratio=3/2'

4. timezone

The field under validation must be a valid timezone identifier according to the timezone_identifiers_list PHP function, like America/New_York or Africa/Abidjan.

5. filled / present / required

Finally, there are three rules which may look really really similar. But they are slightly different.
  • required - The field under validation must be present in the input data and not empty
  • present - The field under validation must be present in the input data but can be empty.
  • filled - The field under validation must not be empty when it is present.
You can take a look at the full list of the rules on the official documentation page. Of course, if you need more rules, you can add your own custom ones. Taylor has recently written that it will be easier in Laravel 5.5. Any other "interesting" validation rules I've missed here?

No comments or questions yet...

Like our articles?

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

Recent Premium Tutorials