How to add my validation in Laravel Validator?

1

In% with both 4 and 5, we have class Laravel , which allows specific validations.

By default there are several, such as Validator , required , email , and others.

But I would also like to be able to validate a phone number with ddd .

Example:

 $valores = ['telefone' => '(31)9995-5088'];

 $rules = ['telefone' => 'required|minha_validacao_de_telefone']

 Validator::make($valores, $regras);

How could I do to add a phone validation in same ?

Is there any way to add a regular expression in the validation of Laravel ?

    
asked by anonymous 10.03.2016 / 17:21

1 answer

3

Yes, in Laravel you can add your own validation.

In Laravel 4 , just add the following code in the file app/start/global.php :

Validator::extend('telefone-com-ddd', function ($attributes, $value) {

    return preg_match('/^\(\d{2}\)\d{4,5}-\d{4}$/', $value) > 0;
});

To use, you can do this:

 Validator::make($valores, ['telefone' => 'required|telefone-com-ddd']);

In Laravel 5 , you have to create a ServiceProvider for your custom Validator :

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ValidatorServiceProvider extends ServiceProvider {

    public function boot()
    {
        $this->app['validator']->extend('telefone', function ($attribute, $value)
        {
             return preg_match('/^\(\d{2}\)\d{4,5}-\d{4}$/', $value) > 0; 
        });
    }

    public function register(){}
}

After that, you need to add the name of this class in config/app.php

'providers' => [
    // Other Service Providers

    \App\Providers\ValidatorServiceProvider::class,
],
    
11.03.2016 / 13:08