June 14, 2017
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.
The field under validation must be yes, on, 1, or true. This is useful for validating "Terms of Service" acceptance.
Used mostly for repeating password, as a confirmation. The field under validation must have a matching field of [field]_confirmation.
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'
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.
You can take a look at the full list of the rules on the
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. 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?
PHP web-developer with 20 years experience, working with Laravel since 2015.
Over the years, published 1000+ videos on YouTube, dozens of full-length courses, hundreds of tutorials and thousands of tweets about Laravel.