Customized Angular 2/4 validator

Asked

Viewed 1,021 times

1

I’m trying to implement a custom validator (Cpf and cnpj) in an angular project using Formbuilder, but when testing the validator, it can’t get the field value.

I created the validator as follows (I am testing only, so the final logic is not implemented):

import { AbstractControl, Validators } from '@angular/forms';

export class Validador {

    static cpf(control: AbstractControl): { [key: string]: any } {
        console.log(control.value);
        if (control.value !== '000.000.000-00') {
            return {cpf: true};
        }
        return null;
    }
}

What happens is that when loading the form page, the console.log is fired 3 times, but returns empty. If I type any value in the field (Ex: 111.111.111-11), the validator is not "triggered" again and maintains the error state.

What could I be doing wrong?

My Formbuilder is as follows:

this.personForm = this.fb.group({
  name: ['', Validators.required],
  cpf: ['', [Validators.required, Validador.cpf]],
  phone: ['', Validators.required],
  email: ['', [Validators.required, Validators.email, Validators.pattern('^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$')]],
  password: ['', Validators.required],
  addressStreet: ['', Validators.required],
  addressNumber: ['', Validators.required],
  addressZipcode: ['', Validators.required],
  addressNeighborhood: ['', Validators.required],
  addressObservation: ['', Validators.required],
  idState: [null, Validators.required],
  addressCity: ['', Validators.required],
});

The country is like this:

<input type="text" class="form-control" placeholder="CPF" formControlName="cpf" mascara="999.999.999-99">
  • Your Validator is seeing if the value is exactly 000.000.000-00, if you type this value continues with error?

  • @Eduardovargas Yes. Whatever value I enter, the error remains. From what I saw, the custom validator is not being triggered by typing any value and submitting the form. Other validators work normally.

  • Console value contains dots and tracus?

  • In fact the console displays blank value at the time of page loading, but after entering a value, it does not display anything on the console. That’s why my suspicion that the validator is not being triggered.

3 answers

2

Change your function to:

  static cpf(control: AbstractControl): { [key: string]: any } {
        console.log(control.value);
        if (control.value !== '000.000.000-00') {
            return {cpfInvalido: 'valor recebido: '+control.value};
        }
        return null;
    }

in html:

{{personForm.get('cpf').errors | json }}

And see if the error value reflects the typed.

  • I did as you mentioned, but the value of the field is not really being passed and does not reflect the "received value".

1

ValidadorCPF(c:AbstractControl) : {[key:string]:boolean} |  null{
  if (c.value !== '000.000.000-00') {
      return { cpf : true};
    }
    else{
      return null;
    }
  }

Declare in your typescript this validation and try again, is the one I use on my system... I just made adptar for your.

  • Thanks for the answer, but it didn’t work either. Considering all the examples I’ve seen so far, I believe the validator itself is correct, the problem is that it is not being triggered when the field value is changed.

  • Your form statement is where? In any method? And how is the form tag of your html?

  • I’m using Formbuilder on ngOnInit. The tag is as follows: <form novalidate [formGroup]="personForm" (ngSubmit)="sendForm()">

0


I found the problem. Actually my validation was correct, but a CPF mask directive I created was causing this bug. I don’t know why, but when removing the mask the validation worked perfectly.

The directive in question is as follows::

import {Directive, ElementRef, Input} from '@angular/core';

declare var Inputmask;
@Directive({
  selector: '[mascara]'
})
export class MascaraDirective {

    @Input() mascara: any;
    constructor(private element: ElementRef) {
        setTimeout(() => {
            Inputmask({ // https://github.com/RobinHerbots/Inputmask
                mask: this.mascara,
                skipOptionalPartCharacter: ' '
            }).mask(this.element.nativeElement);
        }, 500);
    }
}

Browser other questions tagged

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