passing form control value to custom validator angular reactive form

2.3k views Asked by At

There is a custom validator which takes a value as a parameter and checks if the belonged control value is equal to that parameter value or not. the form is reactive form, and the value which should be checked is existing controls value (fisrstname, lastname and email) in form.

the problem is that when the form is created none of the controls (fisrstname, lastname and email) have value, so null will be sent to validation function and then validation does not work, How should this situation be handled?? I am thinking of custom async validator but do not know how to implement and if it is right to think about.

custom validator

public static specialNameValidator(name: string): ValidatorFn {
    return (control: AbstractControl): {[key: string]: any} => {
        if (control.value) {
            return name === control.value.toLowerCase()
                       ? {['specialname'] : {value: control.value}}
                       : null;
        }
    };
}

form creation

private createForm(): void {
        this.signupFrom = this.formBuilder.group({
            firstname: new FormControl(null, Validators.required),
            lastname: new FormControl(null, Validators.required),
            country: new FormControl(null/*, Validators.required*/),
            email: new FormControl(null, [Validators.required, Validators.email]),
            password: new FormControl(null,
                [Validators.required,
                PasswordValidation.NoSpace(),
                PasswordValidation.specialNameValidator(this.model.email),
                PasswordValidation.specialNameValidator(this.model.first_name),
                PasswordValidation.specialNameValidator(this.model.last_name)
                ]),
            passwordconfirm: new FormControl(null, Validators.required)
        },
        // add a validator for the whole group
        { validator: PasswordValidation.PasswordMatch('password', 
          'passwordconfirm')});
    }
0

There are 0 answers