Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading