Laravel custom validation: Make rules that no one breaks!

INANI El Houssain
3 min readMay 15, 2020

--

As a Laravel web developper I’m so grateful to its Validation system, that definitly provides a great set of rules out of the box, that in normal cases are enough to validate all kind of data.

What is good about the framework is not only that it gives a bunch of built-in features but also allows you to extend its functionality and build your own set of rules, that you may get to use it in more than one project.

In this article we will be exploring how to create Custom Validation Rule.

The goal is to validate that form with the following rules :

  • name : required
  • starts_at : required and date
  • ends_at : not required, but if filled must be a date and after starts_at.

1 — Create the Event Request :

It is a good practice to encapsulate your validation rules in the form request object, The controller will thank you later :D

php artisan make:request EventRequest

Normally we would validate the form with the following rules

And as a spoiler let me tell you that it won’t works in the case that we let the ends_at field empty.

2 — Solutions?

Actually we have at least three solution that we can do in here

1 — If you are handling a call from the front end you can detecte if the ends_at field is empty and omit it from the request(not recommended).

2 — To edit the rules depending on its state in the form request like the following.

3 — Create a custom validation rule that we can inject any time

let’s generate the entity thanks to the following command

php artisan make:rule DateIfEmpty

We will have a class that holds three methods :

1 — the constructor if we need any dependency

2 — the message method holding the output of the message incase of failer.

3 — the passes method where we will put our logic (true if it satisfies the condition, false otherwise). $attribute hold the name of the input and $value its value.

So what we want to verify is that :

If the if the value is empty it should passes

if the data is not empty we need to check if its a date input.

And this is how we will be using it inside the EventRequest :

And If you test the form it will passe in all the case.

Upps! What If I need to pass data into it?

In that case we will be passing throught the constructor :

In the Rule validation we can make use of it :

— That’s the end hope you liked it, and make rules that no one breaks!

--

--