Rafael de Castro
Rafael de Castro

Reputation: 1068

Form INVALID due to CustomValidator applied on NON-required form field

I have this form:

    this.form = new FormGroup({
        someField: new FormControl(''),
        someOtherField: new FormControl(''),
        cpf: new FormControl('', [ CustomFormValidators.isValidCPF ]),
    });

And this CustomValidator:

    static isValidCPF(control: AbstractControl): ValidationErrors | null {
    
        const cpf: string = String(control.value);
        const validCPF = CustomFormValidators.sanitizeCPF(cpf);
    
        if ( CustomFormValidators.validateCPF( validCPF ) ) return null; //Success
            
        return { isValidCPF: true }; //Error
    }

MY PROBLEM IS:

On my form the field CPF is not required, so the user may leave it empty. But my CustomValidator is triggering the error, therefore my form is invalid, and will not submit until otherwise.

I tried put this condition on the method with no success:

    if(!control.value){
            if(control.errors && !control.errors.hasOwnProperty('required')){
            return null;
        }
    }

Aditional information:

The code bellow is just in case some wonder. But it's not broken or wrong. It works 100% perfectly. It may have typos on variable names, cause I had to change for the question. But the code bellow is not the issue

    private static sanitizeCPF(cpf): string{
        return cpf.replace(/[^\s\d\ ]*[\s]?[\s\\\^]?/g,'');
    }
        
    private static validateCPF(cpf: string, verifier?): boolean {
        let sum = 0;
        let rest;
        const x = verifier ? 0 : 1;
    
        for (let i = 1; i <= (9 + x); i++){
            sum = sum + parseInt(cpf.substring(i-1, i)) * ((11 + x) - i);
        }
        rest = (sum * 10) % 11;
    
        if ((rest == 10) || (rest == 11)) { rest = 0; }
        if (rest != parseInt(cpf.substring((9 + x), (10 + x))) ) { return false; }
    
        if(!verifier) { return CustomFormValidators.validateCPF(cpf, true); }
    
        return true;
    }

Upvotes: 0

Views: 25

Answers (1)

kvetis
kvetis

Reputation: 7331

in Angular it is usual not to validate empty inputs - because that is the job of the required validator.

Simply skip the validation when the input is empty:

static isValidCPF(control: AbstractControl): ValidationErrors | null {
     
  
    const cpf: string = String(control.value);
    // -------------
    if (!cpf) return null;
    // -------------
    const validCPF = CustomFormValidators.sanitizeCPF(cpf);

    if ( CustomFormValidators.validateCPF( validCPF ) ) return null; //Success
        
    return { isValidCPF: true }; //Error
}

Upvotes: 1

Related Questions