Home > other >  Angular strict mode breaking CustomValidator on email form field
Angular strict mode breaking CustomValidator on email form field

Time:10-05

I'm defining an email form field:

this.form.addControl('email', new FormControl('', [
    Validators.required, CustomFormValidators.isValidEmail
]));

And using a CustomFormValidators class with a isValidEmail method

static isValidEmail(control: AbstractControl): ValidationErrors | null {

    if (!control) return; // <- ERROR HERE

        const regex = new RegExp(..email regex..);
        if (regex.test(control.value)) return null;

        return { isValidEmail: true };
    }

And, with Angular new strict mode rules I'm getting this error:

Type 'undefined' is not assignable to type 'ValidationErrors | null'.

I could not figure it out how to solve this error.

CodePudding user response:

Like the signature indicates, the return value has to be ValidationErrors or null.

The return instruction implicitly returns undefined instead of null which explains the error you observe.

Write this instead:

if (!control) return null;

Or just remove this line as the condition may never evaluate to true (a control instance is always being passed as a parameter of a validator)

  • Related