Home > Enterprise >  Type 'void' is not assignable to type 'ValidationErrors'
Type 'void' is not assignable to type 'ValidationErrors'

Time:04-07

export class MustMatchDirective implements Validator {
    @Input('mustMatch') mustMatch: string[] = [];

    validate(formGroup: FormGroup): ValidationErrors {
        return MustMatch(this.mustMatch[0], this.mustMatch[1])(formGroup); <-error here
    }
}
export function MustMatch(controlName: string, matchingControlName: string) { 
    return (formGroup: FormGroup) => { 
        const control = formGroup.controls[controlName]; 
        const matchingControl = formGroup.controls[matchingControlName]; 
        if (matchingControl.errors 
            && !matchingControl.errors.confirmedValidator) { 
            return; 
        } 

        if (control.value !== matchingControl.value) { 
            matchingControl.setErrors({ confirmedValidator: true }); 
        } else { 
            matchingControl.setErrors(null); 
        } 
    } 
}

May I know what's wrong with the code?

CodePudding user response:

The arrow function returned inside MustMatch function needs to return something, currently it returns void (like the error tells you). It needs to return ValidationErrors | null.

export class MustMatchDirective implements Validator {
    @Input('mustMatch') mustMatch: string[] = [];

    validate(formGroup: FormGroup): ValidationErrors | null {
        return MustMatch(this.mustMatch[0], this.mustMatch[1])(formGroup); <-error here
    }
}
export function MustMatch(controlName: string, matchingControlName: string) { 
    return (formGroup: FormGroup): ValidationErrors | null => { 
        const control = formGroup.controls[controlName]; 
        const matchingControl = formGroup.controls[matchingControlName]; 
        if (matchingControl.errors 
            && !matchingControl.errors.confirmedValidator) { 
            return null; 
        } 

        let error: ValidationErrors | null;
        if (control.value !== matchingControl.value) {
            error = { confirmedValidator: true };
        } else {
            error = null; 
        }
        matchingControl.setErrors(error);
        return error;
    } 
}
  • Related