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?
– Eduardo Vargas
@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.
– jflizandro
Console value contains dots and tracus?
– Eduardo Vargas
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.
– jflizandro