Do you know all the validation rules available in Laravel? Think again! Laravel has many ready-to-use validation rules that can make yo...
Do you know all the validation rules available in Laravel? Think again! Laravel has many ready-to-use validation rules that can make your code life a whole lot easier. Let’s uncover the top 10 validation rules you probably didn’t know existed.
Want to make sure a field is not present in the input? Use prohibited
.
'username' => 'prohibited',
If username
is included in the request, validation will fail. Simple and effective, especially for a honeypot!
Need a field to prohibit another field from being present? Check this out.
'password' => 'prohibits:username',
If password
is present, username
must not be.
This one’s a lifesaver when you need conditional validation.
'email' => 'required_if:contact_method,email',
The email
field is required only if contact_method
is email
.
Opposite of required_if
. Use it to require a field unless another field has a specific value.
'email' => 'required_unless:contact_method,phone',
Here, email
is required unless contact_method
is phone
.
This rule is great when you need a field only if another field isn’t present.
'email' => 'required_without:phone',
If phone
isn’t provided, email
must be.
Step up your game by requiring a field if none of the other specified fields are present.
'email' => 'required_without_all:phone,address',
If neither phone
nor address
is present, email
is required.
Check if a string starts with a given value.
'username' => 'starts_with:admin,user',
The username
must start with either admin
or user
.
Similarly, check if a string ends with a specific value.
'username' => 'ends_with:_admin,_user',
The username
must end with either _admin
or _user
.
Confirm a field’s value exists in another array field.
'selected_option' => 'in_array:available_options.*',
The selected_option
must be one of the values in the available_options
array.
Make sure two fields have different values.
'new_password' => 'different:current_password',
The new_password
must be different from the current_password
.
So there you have it, folks! Ten super handy Laravel validation rules you might not have known about. Using these can save you time and make your code cleaner and more efficient.
All the above have been previously shared on our Twitter, one by one. Follow us on Twitter; You'll ❤️ it.
You can also check the first article of the series, which is on the Top 5 Scheduler Functions you might not know about. Keep exploring, and keep coding with ease using Laravel. Until next time, happy coding! 🚀
Subscribe to our "Article Digest". We'll send you a list of the new articles, every week, month or quarter - your choice.
What do you think about this?
Wondering what our community has been up to?