Is there a way to clear the field formatting before going through validation?

Asked

Viewed 230 times

3

I’m trying to search the net how I solve this and it’s taking a long time, it seems to be something simple but I’m breaking my head, 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 you have the CNPJ field that has a Mask that formats it (e.g.: 52,836,639/0001-05). This field is being stored in the database without formatting, only with the numbers (e.g. 52836639000105).It is a CHAR field(14).

Validation is being done by a Request (Empresarequest) with the following Ules

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

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

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

I put this in the boot of Appserviceprovider:

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

The question is:

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

  • How are you doing this formatting? Before you insert it in the BD? to transform "52.836.639/0001-05" into "52836639000105" as you do?

  • @Miguel, in the method store I’m making a simple replace $data['cnpj'] = str_replace(['-', '/', '.'], '', $data['cnpj']); before the Empresa::create($data);

2 answers

2


Here’s what you can do:

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 your error message you can go to the lang/validation.php file:

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

More about this (custom validation Rules)

Or a little simpler, without having to extend:

I assume you’re receiving the input input form as argument:

...
$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
}
  • Thanks, it worked out! I just had to modify the query a little:

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

  • Ha ok, I get it @Lucasmartins, anyway you got a solution down if it suits you better

  • is only in query return Empresa::where('cnpj', $value)->get()->except($this->empresa)->count() == 0; In order for it not to compare the CNPJ of the same record when updating, I added the except($this->empresa)

  • Ha ok, I understood yes @Lucasmartins, sorry I didn’t have that information. But now is rersolvido (:

1

Try to use the function all().

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;
}

Browser other questions tagged

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