Custom Validation Rules in Laravel 5.5

In this blog on Laravel, we discuss the various custom validation rules in Laravel 5.5. Using a simple form and example, we have discussed the step by step process of creating the custom validation rule, which includes creating rule classes, adding validation rules and classes. We have also used and tested the validation rules in this blog. Read in detail.

Custom Validation Rules in Laravel 5.5

The biggest advantage of Laravel over other frameworks is the fact that it comes with a lot of built-in features. We have explored the best security practices and Laravel Helpers in our previous articles. In this article, we are going to understand Laravel Custom Validation Rules.

Laravel provides you with a rich set of validation rules which you can add to validate the requests. Laravel allows you to define the validate method which is part of the existing Request object. When the validation rule passes, your code gets executed further, else you can show an error message.

12

As you can see in the above code, we are intercepting the call. Just before the actual store of data is happening, we are validating the request. We are checking if the blog we are about to save is unique as well as its length is less than 255. We have also mentioned that the body is mandatory for a blog to be valid. Only if all these rules are validated then the request will go forward.

Another advantage is we can redirect the user to a specific page when an error occurs. By default, Laravel takes the user back to the same page in case of error. In our case, it will reload the same page and hit the create method. In that method, we check if there are any errors, we show him the error page.
11

In most instances, the rules provided by Laravel are sufficient enough to validate all the use cases, but in certain conditions, you might need to add custom validation rules. Let’s dive deep and take a look into how we can define custom rules and enable them to validate our requests.

Creating Custom Validation Rules in Laravel

Laravel provides a very elegant solution to create custom validation rules and hook all those rules to your custom classes.

Before we dig deeper, let us create a very simple form, where the customer has to enter a name and email address.
You can use the below command to create a request

php artisan make:request StoreCustomerRequest

Once you execute the above command, the following class will be added.

10

As you can see there are two methods which are already present in the class:

  • Authorize method: It is used to define the authorization rules. It can help you in determining who all has access to these pages.
  • Rules method: This is the method where you would be adding your validation rules. We are validating names and emails.

laravel-cta-first

Creating Rule Class

As we have just seen, we have created a Customer Model that has a name and email. Now let us add some rules to validate these fields. You can execute the below command to create a custom rule.

PHP artisan make: rule UpperCase

Once you execute this command, Laravel creates a new folder called Rules in the app folder. It will also add the UpperCase.php file class file at the same location.
9
As you can see there are two functions which we need to implement in the above class. These are passes() and message().

Adding Validation Logic

Once we have added the validation rule class, let us add the validation logic also. For this example, lets us consider that the name is in upper case format. So we will go ahead and update our passes function.

8

As you can see in the passes() method, we are initially converting our value to the upper case and checking if the passes value and the converted value are the same. If they are the same, we return true else we are returning false.

As a good coding practice, we should update the message() function. In the message() function, we are specifying the message that would be shown, in case if the validation error happens.

7

In the function, we are returning the error string that should be displayed in case one of the validation rules fails.

Using the Validation Rule in Form Request Class

Now that we have created the validation rule, let us go ahead and add the validation in the form request class which we had added above.

The first step would be to import this newly created class into our request class. We can import using the below code:
use App\Rules\UpperCase

Now that we have imported the class, let us go ahead and update and update the rules() method.

6

As you can see, we now have added an extra validation in the name rules list. We are creating a new instance of the UpperCase class. When the rules() method will get executed, the UpperCase class will be instantiated and it will call the passes() method in the Uppercase class to validate the name.

If the name is not in the upper case, the pass() method will return false, post which the rules() method will call the message() function to get the error message.

Using the Validation Rule in Controller

The above method of adding the rule in the form request is useful when you are creating the request object. The rules class can also be added directly to the controller code. Let us quickly see how we can implement the UpperCase rules class directly in the controller.

Again, the first step would be to import the UpperCase directly in the controller class. We can use the below code to directly import the class.

use App\Rules\UpperCase

Once you have imported the class, the next step would be adding in the validate call.

5

As you can see in the request validate function, we added a new rule in name validation. We are creating a new object of the UpperCase class. During this call, a new object of UpperCase will be created, and validation will take place.

Creating Custom Validation in Laravel Using Exits Rule

Apart from creating rules class for custom validations, we can also use closures and extends to implement our custom validation logic.
laravel-cta-second

Using Custom Validation

Before we dig deeper into extends and closure, let us make our understanding of creating rules clearer. We are going to implement a custom rule which is going to check if the number passed in the text box is even or not.

So, the first step to create this rule would be to create our rules class. We should use the make: rule command which is provided by the artisan. You can use the below command to create our rule class.

php artisan make:rule IsEvenNumber

Once you execute this command, a ruling class would be generated for you in the app/Rules directory. Below would be the bare minimum code which would be added by the Laravel framework itself

4

As soon as we execute the command, the above class is generated. It has two functions which we need to implement. One of these functions is passes() which returns if the validation has passed or not. The other function is the message() which allows you to customize your error message.

In the passes function, we can just validate by taking modulo, if the number is even or not. Now that we have defined the rule, we can use it easily.

use App\Rules\Uppercase;

$request->validate([
'name' => ['required', 'string', new IsEvenNumber],
]);

Custom Validation Rule Using Closures

Now that we have seen how we can create our custom validation rules using the make: rule command, we should understand how we can create commands using closures. The concept of validation rule remains the same, it is just implemented in a different form.

3

As we can see in the above code, we are using the Validator class and directly making the rule. The function in it is getting 3 values: attribute, value, and fail. The attribute is the field for which the validation is happening. The value corresponds to the actual value of the said object and failure is the callback method that would be executed once the validation fails.

Validation Rule using Extend method

One more way to add a validation rule is by using the extend method. The validator façade has this extended method. If you are going to use the validator only in one place, it might be a good idea to define the validation rule using the extend method.

So let us go ahead and create a validation rule.

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;

class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}

/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Validator::extend(‘uppercase’, function ($attribute, $value, $parameters, $validator) {
return $value === strtoupper($value);
});
}
}

As you can see, in the boot() method we have added the call for Validator:: extend() method. In this method, we are adding our validation rule. Again, this validator gets four inputs: attribute, value, parameter, and validator.
laravel-cta-third

Custom Validation Rules Example

Now that we have understood all the concepts of custom validation rules in Laravel. Let us write one more complex example to be perfect. In this example, a user is supposed to enter a year and city.

2 1

The rules we are going to apply for the year as follows:

  • The Olympic games had started in 1896
  • The year cannot be bigger than the current year
  • And since the Olympics happen every 4 years, the number should be divisible by 4

So, let us go ahead and create these rules. You can execute the below artisan command to create the ruling class.
php artisan make:rule OlympicYear

Once you have executed this command, Laravel would generate the ruling class called the OlympicYear.php file. The file is located in the app/Rules/ folder.

Let us go and check the content of the newly generated file.

1

So as we can see the above file contains two major functions: passes() and message(). You should add all your validation logic in the passes() function. It should return true or false based on the logic you have written in the function. The message() function returns a string that specifies the error message to be displayed in case the validation fails.

Let us go ahead and call the rules we had specified in the problem. We want the year to be greater than 1896, less than today, and should be divisible by 4.
public function passes ($attribute, $value)
{
return $value >= 1896 && $value <= date('Y') && $value % 4 == 0;
}

So, we are returning the output as true or false based on the condition. The value we are getting in the function input is the actual value that the user has entered.

We should always fill the message with some correct values so that the user can easily understand, at what step he has made a mistake and he can correct it.

public function message()
{
return ':attribute should be a year of Olympic Games';
}

As you can see from the above function, we are returning a string that alerts the user the value entered in the field should be the correct Olympic year.

Now that we have defined the class, the next logical step would be to integrate it with our controller. Just before saving our values, we should always validate the values.
public function store(Request $request)
{
$this->validate($request, ['year' => new OlympicYear]);
}

In the above code, in the store() function, we are validating the call. If you would notice, we are creating the new object and passing the same to the validate call. The next time,this code gets hit, our newly written class would be created and the passes() function would be called which would determine if the value entered by the user is valid or not.

Conclusion

Laravel is used extensively in web development. One major advantage of Laravel as compared to a similar framework is the level of customization it provides. It also comes with most of the functionality built in. Laravel has a very set of validators that can be used to validate the request forms or the input data.

But in certain scenarios, we may need a custom validator that can cater to our specific purpose. Laravel allows you to create these custom validators. In this article, we have explored various ways in which you can add these validators.

You can use the make: rule command to create the ruling class or you can use the Closure and Extends method present in the validator. We also tried to write a complex example of validating the Olympic year. Hope the next time when you have to write a custom validator, you can easily write it.

Harikrishna Kundariya
Harikrishna Kundariya
Harikrishna Kundariya, a marketer, developer, app lover, technology savvy, designer, co-founder, Director of eSparkBiz @Mobile App Development Company where you can Hire Mobile App Developer. His 8+ experience enables him to provide digital solutions to new start-ups based on app development.
Blog CTA
  • This field is for validation purposes and should be left unchanged.

Related Post

Top Advantages of Laravel Frameworks In Detail

Top Advantages of Laravel Frameworks In Detail

Laravel has elevated the satisfaction of the PHP developers to new heights...

Analyzing Laravel Performance Optimization Tips In Detail

Analyzing Laravel Performance Optimization Tips In Detail

Since 2011, Laravel has gained a lot of popularity. Most of the organizati...

Surveying The Popular Sites Built With Laravel

Surveying The Popular Sites Built With Laravel

Laravel is an open-source framework for web application development writte...

Your information is safe with us. eSparkBiz guarantees 100% data security. We don’t use emails for spamming.

  • By clicking Inquire Now, you accept eSparkBiz's Terms of Use and Privacy Policy and agree to your personal data collection and use.
  • This field is for validation purposes and should be left unchanged.