How To Create Custom Validation Rules With Laravel 5

How To Create Custom Validation Rules With Laravel 5

In this post we will give you information about How To Create Custom Validation Rules With Laravel 5. Hear we will give you detail about How To Create Custom Validation Rules With Laravel 5And how to use it also give you demo for it if it is necessary.

How To Create Custom Validation Rules With Laravel 5

Laravel provides so many helpful validation rules but if you want to define your own validation rules in Laravel 5 then you can easily define your own validation rules and then you can use your custom validation rules in your application whenever you need.

In this tutorial, I will tell you step by step to create custom validation rules to validate Indian phone number that start from +91.



Step 1: Add Routes

In first step, we will add two routes, First route will help to render view and second route will handle the post request.

Add this two routes in your routes.php file.


app/Http/routes.php

  1. Route::get('custom-validation',['as'=>'custom-validation.get','uses'=>'CustomValidatorController@getCustomValidation']);
  2. Route::post('custom-validation',['as'=>'custom-validation.post','uses'=>'CustomValidatorController@postCustomValidation']);
Route::get('custom-validation',['as'=>'custom-validation.get','uses'=>'CustomValidatorController@getCustomValidation']);
Route::post('custom-validation',['as'=>'custom-validation.post','uses'=>'CustomValidatorController@postCustomValidation']);


Step 2: Create Controller

In this step, we will create a CustomValidatorController.php file and put following code.


app/Http/Controllers/CustomValidatorController.php

  1. <?php
  2. namespace AppHttpControllers;
  3. use IlluminateHttpRequest;
  4. use AppHttpControllersController;
  5. class CustomValidatorController extends Controller {
  6. public functiongetCustomValidation(){
  7. returnview('customvalidation');
  8. }
  9. public functionpostCustomValidation(Request $request){
  10.     $this->validate($request,[
  11.      'phone'=>'required|in_phone',
  12.      ]);
  13.      return'successfully';
  14. }    
  15. }
<?php
namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppHttpControllersController;

class CustomValidatorController extends Controller {

    public function getCustomValidation(){
     
        return view('customvalidation');
    }
    public function postCustomValidation(Request $request){
    	$this->validate($request, [
	        'phone' => 'required|in_phone',
	    ]);
	    return 'successfully';
    }	
}


Step 3: Use the extend method on the Validator facade in AppServiceProvider

Basically the custom validator Closure takes four arguments :

  • $attribute
  • $value
  • $parameters
  • $validator

Ok now we will write code for new custom validation rules.


app/Providers/AppServiceProvider.php

  1. <?php
  2. namespace AppProviders;
  3. use IlluminateSupportServiceProvider;
  4. use Validator;
  5. class AppServiceProvider extends ServiceProvider
  6. {
  7. public functionboot()
  8. {
  9. Validator::extend('in_phone',function($attribute,$value,$parameters){
  10. returnsubstr($value,,3)=='+91';
  11. });
  12. }
  13. public functionregister()
  14. {
  15. }
  16. }
<?php

namespace AppProviders;

use IlluminateSupportServiceProvider;
use Validator;
class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
       Validator::extend('in_phone', function($attribute, $value, $parameters) {
            return substr($value, 0, 3) == '+91';
        });
    }
    public function register()
    {
    }
}

In above code, in_phone is a rule name that will use later when i need to validate any phone number which must be start from +91.


Step 4: Define error message

Now, we will define custom error message for new validation rules.


resoueces/lang/en/validation.php

  1. 'custom'=>[
  2. 'phone'=>[
  3. 'in_phone'=>'Please enter Indian phone number which starts with +91',
  4. ],
  5. ],
'custom' => [
    'phone' => [
        'in_phone' => 'Please enter Indian phone number which starts with +91',
    ],
],


Step 5: Create View

In this last step, we will create a view file where we can check this validation rules.

So create a customvalidation.blade.php file in following path resoueces/view/


resoueces/view/customvalidation.blade.php

  1. <htmllang="en">
  2. <head>
  3.     <title>Laravel 5 : Custom Validation Rule</title>
  4.     <linkrel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  5. </head>
  6. <body>
  7.     <divclass="container">
  8. {!! Form::open(array('route' => 'custom-validation.post','method'=>'POST')) !!}
  9.             @if (count($errors) > 0)
  10.              <divclass="alert alert-danger">
  11.              <ul>
  12.              @foreach ($errors->all() as $error)
  13.              <li>{{ $error }}</li>
  14.              @endforeach
  15.              </ul>
  16.              </div>
  17.             @endif
  18.             {!! Form::text('phone', old('phone'), ['placeholder' => 'Enter Indian phone number']) !!}
  19.             <br/>
  20.             {!! Form::submit('Save') !!}
  21.         </form>
  22.     </div>
  23. </body>
  24. </html>
<html lang="en">
<head>
	<title>Laravel 5 : Custom Validation Rule</title>
	<link rel="stylesheet" href="#" >
</head>
<body>
	<div >
       {!! Form::open(array('route' => 'custom-validation.post','method'=>'POST')) !!}
			@if (count($errors) > 0)
			    <div >
			        <ul>
			            @foreach ($errors->all() as $error)
			                <li>{{ $error }}</li>
			            @endforeach
			        </ul>
			    </div>
			@endif
			{!! Form::text('phone', old('phone'), ['placeholder' => 'Enter Indian phone number']) !!}
			<br/>
			{!! Form::submit('Save') !!}
		</form>
	</div>
</body>
</html>

Click here to see demo..

Show Demo

Hope this code and post will helped you for implement How To Create Custom Validation Rules With Laravel 5. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

  +  63  =  67

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US