0

有一个自定义验证器将值作为参数并检查所属控件值是否等于该参数值。表单是reactive form,应该检查的值是表单中现有的控件值(名字、姓氏和电子邮件)。

问题是当创建表单时,所有控件(名字、姓氏和电子邮件)都没有值,所以 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')});
    }
4

0 回答 0