How to add my validation in Laravel Validator?

Asked

Viewed 1,419 times

1

In the Laravel, both the 4 and the 5, we have the class Validator, which allows specific validations to be made.

By default there are several, such as required, email, same 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 add a phone validation on Laravel?

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

1 answer

3


Yes, in the Laravel you can add your own validation.

In the Laravel 4, just add the following code to 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 so:

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

In the Laravel 5, you have to create a ServiceProvider concerning your Validator costumed:

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, it is necessary to add the name of this class in the config/app.php

'providers' => [
    // Other Service Providers

    \App\Providers\ValidatorServiceProvider::class,
],

Browser other questions tagged

You are not signed in. Login or sign up in order to post.