Is there a way to clear field formatting before going through validation? [duplicate]

3

I'm trying to look on the net as I solve this and it's taking a lot of time, it seems to be something simple but I'm breaking my head, so I decided to create a post here.

I'm using Laravel 5.3 with MySQL in an environment provided by Laravel Homestead.

In a company registration form there is the CNPJ field that has a mask that formats it (eg: 52.836.639 / 0001-05). This field is being stored in the database without formatting, only with the numbers (eg 52836639000105). It is a CHAR (14) field.

Validation is being done by a Request (EnterpriseRequest) with the following rules

public function rules()
   {
       return [
           'razao_social' => 'bail|required|max:128',
           'nome_fantasia' => 'required',
           'cnpj' => 'bail|required|unique:empresas|max:14'
       ];
   }

But unique and max:14 does not work, because the data is coming formatted (with '.', '-' and '/') and the database is not.

I've tried to use an event to test a possible fix, but it's still the same:

I put this in the AppServiceProvider :

Empresa::saving(function ($empresa) {
    $empresa->cnpj = 12345678912345; // 14 characteres
});

The question is:

In this validation mode, is there a way to clear the CNPJ formatting before going through validation?

    
asked by anonymous 20.12.2016 / 18:07

2 answers

2

You can do the following:

use Validator;
...


public function rules() {
    Validator::extend('cnpj_unique', function ($attribute, $value, $parameters, $validator) {
        $value = str_replace(['-', '/', '.'], '', $value); // tranformar input no mesmo formato que pode estar na BD
        return Empresa::where('cnpj', $value)->count() == 0; // verificar se já existe
    });

    return [
       'razao_social' => 'bail|required|max:128',
       'nome_fantasia' => 'required',
       'cnpj' => 'cnpj_unique|bail|required|max:14' // aqui colocas a tua nova rule costumizada
    ];
}

To add to your error message you can go to the lang / validation.php file:

...
"cnpj_unique" => "cnpj já existe",
...

More on this (custom validation rules)

Or a little simpler, without having to extend:

I suppose that you are receiving the data to be sent as an argument the inputs coming from the form:

...
$inputs = $request->all();
$inputs['cnpj'] = str_replace(['.', ',', '/'], '', $inputs['cnpj']);

$validator = Validator::make($inputs, $this->rules());
if ($validator->fails()) {
    // falhou, redirect e enviar erros para o utilizador
}
    
20.12.2016 / 18:25
1

Try to use the all() function.

public function rules(){
   return [
       'razao_social' => 'bail|required|max:128',
       'nome_fantasia' => 'required',
       'cnpj' => 'bail|required|unique:empresas|max:14'
   ];
}

public function all(){
   $input = parent::all();

   $cnpj = str_replace(['.', ',', '/'], '', $input['cnpj']);

   $input['cnpj'] = $cnpj;
   return $input;
}
    
20.12.2016 / 18:24