1 juillet 2015

How to add new Validators to Laravel 5.1

Par Jean-Marc Amon

 

laravel-5.1lts-en

Laravel 5.1 comes with new features like the « Form Request » which reveal themselves to be very useful when validating forms. All you have to do is to define the validation rules and the whole validation process is handled automatically in the background.

For the example, we will use the one on theLaravel site. Create a new Form Request with command line

php artisan make:request StoreBlogPostRequest

Add validation rules

/**
 * Determine if the user is authorized to make this request.
 *
 * @return bool
 */
public function authorize()
{
    return true;
}

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ];
}

Then in the controller, the method responsible for handling the form must suit the following

/**
 * Store the incoming blog post.
 *
 * @param  StoreBlogPostRequest  $request
 * @return Response
 */
public function store(StoreBlogPostRequest $request)
{
    // The incoming request is valid...
}

There is a list of all Laravel bult-in validators  see how to add new ones.

First we will create a new file named Validators.php in app/Http/Validators.php.

 /**
     * Bootstrap any application services.
     *
     * @param Factory $validator
     */
    public function boot(Factory $validator)
    {
        require_once app_path() . '/Http/Validators.php';
    }

Then add the new validator as follows

<?php


$validator->extend(
    'valid_password',
    function ($attribute, $value, $parameters) {
        return preg_match('/^[a-zA-Z0-9!@#$%/^&*()-_+=|[]{}\\?.,<>`'":;]+$/u', $value);
    }
);

$validator->extend(
    'phone_number',
    function ($attribute, $value, $parameters) {
        return 10 === strlen(preg_replace('#^.*([0-9+]{10})$#', '$1$2$3', $value));
    }
);

$validator->extend(
    'permission',
    function ($attribute, $value, $parameters) {
        return preg_match('/^[a-zA-Z]+(.{1}[a-zA-Z]+)?$/', $value);
    }
);


$validator->extend('alpha_spaces', function ($attribute, $value) {
    return preg_match('/^[pLs]+$/u', $value);
});

You can now add these new rules (valid_password, phone_number, leave, alpha_spaces) in your validations rules. The corresponding error messages must be added in the language files located in resources /lang/en/validation.php

return [

...
'alpha_spaces' => 'The :attribute must contains only letters and spaces.',
'phone_number' => 'The :attribute must contains only numbers and + .',
...
];

That it is a method among others.