关键字的Angular 2强制自定义验证

For*_*stG 5 validation angular2-formbuilder angular

我有这个代码:

this.form = fb.group({
        username: ['', Validators.compose([Validators.required])],
        fullName: ['', Validators.compose([Validators.required])],
        password: ['', Validators.compose([Validators.required])],
        confirmPassword: ['', Validators.required],
    }, {validator: matchingPasswords('password', 'confirmPassword')});
Run Code Online (Sandbox Code Playgroud)

matchingPasswords:

export function matchingPasswords(passwordKey: string, passwordConfirmationKey: string) {
return (group: FormGroup) => {
    let password = group.controls[passwordKey];
    let passwordConfirmation = group.controls[passwordConfirmationKey];
    if (password.value !== passwordConfirmation.value) {
        return passwordConfirmation.setErrors({mismatchedPasswords: true})
    }
}
Run Code Online (Sandbox Code Playgroud)

}

HTML:

<div class="form-group">
        <input [formControl]="confirmPassword" class="form-control checking-field" type="password">
        <span class="help-block text-danger" *ngIf="form.get('password').touched && form.get('password').hasError('required')">
</div>
<div class="form-group">
        <input class="custom-control-input checkbox-main" type="checkbox" [(ngModel)]="policyButtonValue" [ngModelOptions]="{standalone: true}" ngDefaultControl>
        <span class="custom-control-indicator"></span>
</div>
Run Code Online (Sandbox Code Playgroud)

这是功能性的,并且运行良好,但我有一个特殊的用例场景应该修复.

  1. 单击第一个密码字段.
  2. 填写密码,例如:"foo"
  3. 单击确认密码字段.
  4. tpye在同一件事,例如:"foo" 在此输入图像描述 直到这一点,没有问题.
  5. 在确认密码字段中键入不同的内容,例如:"foobar"(此时验证器显示此处存在错误) 在此输入图像描述
  6. 单击密码字段
  7. 键入与密码字段相同的内容:"foobar",此处,确认密码字段仍然无效,直到密码字段失去焦点... 在此输入图像描述 有没有办法,强制matchupPassword验证在keyup事件上运行,而不是现在如何工作?

pix*_*its 5

你需要一个else块:

if (password.value !== passwordConfirmation.value) {
    passwordConfirmation.setErrors({mismatchedPasswords: true})
}
else {
    passwordConfirmation.setErrors(null);
}
Run Code Online (Sandbox Code Playgroud)