I am trying to implement a custom validator (cpf and cnpj) on an angular project using FormBuilder, but when testing the validator, it can not get the value of the field.
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 enter any value in the field (Ex: 111.111.111-11), the validator is not "fired" again and keeps the error state.
What can I be doing wrong?
My FormBuilder looks like this:
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 field looks like this:
<input type="text" class="form-control" placeholder="CPF" formControlName="cpf" mascara="999.999.999-99">