将表单控件值传递给自定义验证器角度反应形式

时间:2017-09-15 14:25:21

标签: forms angular angular-reactive-forms custom-validators angular-validation

有一个自定义验证器,它将一个值作为参数,并检查所属的控制值是否等于该参数值。表单为reactive form,应检查的值为表单中的现有控件值(fisrstname,lastname和email)。

问题是,当创建表单时,没有任何控件(fisrstname,lastname和email)具有值,因此null将被发送到验证函数,然后验证不起作用,应如何处理这种情况?我在考虑custom async 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;
        }
    };
}

表单创建

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 个答案:

没有答案