Web Development 4 min read

Custom Validation Rules in Laravel 5.5

Written on 23 Aug 2017
Overview

In Laravel 5.5 an artisan command was introduced to allow for custom validation rules. Knowing how to take advantage of this is helpful for creating a web application based on the Laravel framework.

Laravel, the industry’s most popular PHP framework, comes with a variety of built in features, including premade validation rules to handle your application’s input forms. However, as of Laravel 5.5, there’s a great artisan feature to specify custom rules using the rule object. This comes in handy when making a custom Laravel application that may have unique input data. This blog post will provide a short intro on deploying custom validation rules.
laravel-and-custom-validation
Below we’ve provided some same code, written for an app that needs to verify a particular github repository. The way this was done was by creating an API call straight to GitHub. You can register your own custom validation rules by using the rule object. In order to generate a new custom rule object, you just need to define the class using two methods (‘passes’ and ‘message’). From here, you place your class into the App/Rules namespace. As an alternative, to create the rule class, you can run
namespace App\Rules;     
use App\Source;     
use Illuminate\Contracts\Validation\Rule;     
class ValidateRepository implements Rule{     
public $source;     
public $branch;     
public function __construct($source, $branch){     
$this->source = $source;     
$this->branch = $branch;     
}     
public function passes($attribute, $value){     
if (! $this->source instanceof Source) {     
return false;     
}     
return $this->source->client()->validRepository($value, $this->branch;);     
}     
public function message(){     
return 'This is not a valid repository.';     
}     
}     
 

This example code is from Taylor Otwell, the creator of Laravel.

The ‘passes’ method will then receive the arguments ‘$attribute’ and ‘$value’ from the Laravel Validator. Under validation, you will find the field name ‘$attribute. ‘$value’ will be the field value.
In this example, the ‘Source’ object is an ELoquent ORM model that represents a repository provider like GitHub.
‘Message’ returns an error message in case validation fails.
Now that we have defined our custom rule for validation, we can use it with a request. We can instantiate it in our rule array using the ‘validate’ method from the Request object in Laravel.
use App\Rules\ValidateRepository;     
$request->validate([     
'repository' => ['required', new ValidRepository($this->source(), $request->branch)]     
]);
Now, let’s take a look at making a similar custom validation rule in order to verify a phone number extension. This can be accomplished by the following steps:
  1.  
First, you will need to add two custom routes in order to render the view and to handle the post request.
app/Http/routes.php     
Route::get('validate-phone', MyValidatorController@getPhoneValidation');     
Route::post('validate-phone', MyValidatorController@postPhoneValidation');
 
Then you will have to create the controller file and add the required methods declared in the routes.
In app/Http/Controllers/MyValidatorController.php     
<?php     
namespace App\Http\Controllers;     
use Illuminate\Http\Request;     
use App\Http\Controllers\Controller;
class MyValidatorController extends Controller {     
public function getPhoneValidation(){     
return view('phone-validation');     
}
public function postPhoneValidation(Request $request){     
$this->validate($request, [     
'phone' => 'required|ph_ext',     
]);
      return 'success';     
}     
}
Next step is to extend the method on the Validator facade in AppServiceProvider. Custom validator Closure takes four arguments : $attribute, $value, $parameters, $validator.     
In app/Providers/AppServiceProvider.php
<?php     
namespace App\Providers;     
use Illuminate\Support\ServiceProvider;     
use Validator;
class AppServiceProvider extends ServiceProvider {     
public function boot(){     
Validator::extend('ph_ext', function($attribute, $value, $parameters) {     
return substr(trim($value), 0, 2) == '+1'; //US country code in phone     
});     
}
public function register(){     
}     
}
When the validation rule will run, you need to show the respective messages.     
In resources/lang/en/validation.php
'custom' => [     
'phone' => [     
'ph_ext' => 'Please enter a phone number with US country code',     
],     
],
Lastly, you need to create the view and test the validation.     
resources/view/phone-validation.blade.php
{!! Form::open(array('route' => 'validate-phone', 'method'=>'POST')) !!}     
@if (count($errors) > 0)     
<div class="alert alert-danger">     
<ul>@foreach ($errors->all() as $error)     
<li>{{ $error }}</li>     
@endforeach</ul>     
</div>     
@endif
{!! Form::text('phone', old('phone'), ['placeholder' => 'Enter a US phone number']) !!}     
<br/>     
{!! Form::submit('Save') !!}     
</form>
You can use your own custom rule from a Form Request, or any other location you need to validate input. This is one of many great features that makes Laravel something PHP developers gravitate towards for their custom applications. Once you’ve got the hang of it, you’ll probably find yourself taking advantage of this feature often.
project manager jobs in kolkata
If you need a custom web application developed, or you have an existing Laravel project that needs updated or maintained, CodeClouds has a team of expert Laravel developers at affordable rates. Contact us to learn more today!
If you are an experienced Laravel developer looking to take the next step in your career or you have experience in leading complex projects, join our development team! We have openings for project manager jobs in Kolkata.

Share this article

806 reads
Contents

Similar Reads