custom validation in laravel

Custom Validation In Laravel

In laravel, there’re plenty of validation rules that exist out of the box, but sometimes we need to create our own custom validation rules to validate incoming requests.

In this post, we will see how to create a custom validation rule in Laravel application.

First, we will create a file to define a validation rule. I’ll create a Validators folder in the app directory and in it create a file named customValidation.php so our full path will be app\Validators\customValidation.php

In this example, we will create a validation to validate phone number, our code will look something like this.

<?php

namespace App\Validator;

use Illuminate\Support\Facades\Log;

class customValidation
{
     public function validatePhone($attribute, $value)
     {
		return preg_match('%^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$%i', $value) && strlen($value) >= 10;

     }
}

Now, we need to register this validation rule to use it in our controller to validate a request. So, let’s do this.

Go to App\Providers directory and put below code snippet in AppServiceProvider.php file in boot method:

public function boot()
{
      $this->app->validator->extend('phone','App\Validator\customValidation@validatePhone');
}

Okay, now we can use this validation rule in any controller using phone. I’ve used it as below code snippet:

public function saveData(Request $request)
{
	 $validator = Validator::make($request->all(), [
	'mobile_no' => 'required|phone',
],[
    'mobile_no.required'=>'Please enter your mobile number',
    'mobile_no.phone'=>'Please enter valid mobile number',
]);
}

You can also define more validation rules in customValidation.php file as per your requirement and then register it in AppServiceProvider.php file.

0 0 votes
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments