3 Reasons Your Laravel Validations Aren't Working

You’ve tried multiple combinations of rules, but invalid data still makes it through. Or valid data can’t make it past validation. Or the validation code throws up an error.

You just want this field to be required and that field to be optional, and maybe be a number. It seems small enough and you just want to sleep instead of fiddling with Laravel validations!

Here are some reasons you might be having trouble:

Reason 1: You aren’t using the right HTML element

Maybe you’re using checkboxes and you want to check that one and only one is checked? Use a radio button instead!

If you want numeric data, you can simplify things by using a number input instead of text field. Though it might be the other way around if you’re looking for a “number” that has leading zeroes, like James Bond’s agent number “007”!

Also, make sure you’re using your HTML elements correctly. If you’re using checkboxes, make sure you’re using them correctly: give all your checkboxes the same name and different values and that will help your validation work. You can check the value instead of checking checkbox names and values.

Reason 2: Your input’s data structure doesn’t lend itself to validation

If you’ve generated your form from an array of information from your database or a configuration array. In this scenario, you might use an ID from that array to separate the form, but now you want to validate against those IDs. The problem is: those IDs are now input array keys, not values.

Remember, your validation rules only really run against the values. What you could do to validate the keys as well is, before validation begins, prepare another array of values using the PHP method array_keys.

Reason 3: Your validation doesn’t fit the Laravel built in validations

Sometimes you have a validation that goes beyond what you can do with Laravel’s string validators. Maybe only specific combinations user responses should be allowed. Laravel’s built in validators have some ability to handle database lookups for you, but maybe you need to use a scope or some other constraint on top of the database lookup.

If you’ve ruled out the other reasons and you still can’t seem to make it work with Laravel’s built in validation, it’s time for a custom validation rule. Laravel gives you a template and base object to create your own rule, where you can do anything you need to validate user input. Then youcan use this rule in any form by importing that class and adding it to your array of rules.

writing

I write about technology I'm using and the tech ecosystem.

speaking

I speak at tech and other events. You can see the recordings/slides.

resume

Here's my work history.

contact me

If you're interested in working together, let me know!