Angular 5形式无效从不'假'

时间:2018-04-18 16:54:58

标签: angular5 angular-reactive-forms

我对此表单代码的唯一更改是为密码匹配添加验证器,现在变量invalid永远不会为false。

表单设置:

this.CreateUserForm = new FormGroup({
  Email: new FormControl(null, Validators.required), // Create Email validator!
  Password: new FormControl(null, Validators.required),
  ConfirmPassword: new FormControl(null, Validators.required),
  FirstName: new FormControl(null, Validators.required),
  LastName: new FormControl(null, Validators.required),
  MiddleInitial: new FormControl(null) // Write custom validators for single character, upper case, letters only
}, PasswordValidation.MatchPassword);

密码匹配:

import { AbstractControl } from '@angular/forms';
export class PasswordValidation
{

    static MatchPassword(AC: AbstractControl)
    {
        var data = AC.value;
        let password = AC.get('Password'); // to get value in input tag
        let confirmPassword = AC.get('ConfirmPassword'); // to get value in input tag
        if (password.value != confirmPassword.value)
        {
            AC.get('ConfirmPassword').setErrors({ MatchPassword: true })
        } else
        {
            AC.get('ConfirmPassword').setErrors({});
            return null;
        }  
    }
}

1 个答案:

答案 0 :(得分:0)

如果有效的没有setErros,只需返回null。

 if (password.value != confirmPassword.value)
    {
        AC.get('ConfirmPassword').setErrors({ MatchPassword: true })
    } else
    {
      // AC.get('ConfirmPassword').setErrors({});
        return null;
    }