【问题标题】:Angular 2 force custom validation on keyupAngular 2 强制对 keyup 进行自定义验证
【发布时间】:2017-03-14 10:00:33
【问题描述】:

我有这个代码:

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')});

匹配密码:

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})
    }
}

}

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>

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

  1. 点击第一个密码字段。
  2. 填写密码,例如:“foo”
  3. 点击确认密码字段。
  4. tpye 在同一件事上,例如:“foo” 到目前为止,没有问题。
  5. 在确认密码字段中输入不同的内容,例如:“foobar” (此时验证器显示这里有错误)
  6. 点击密码字段
  7. 在密码字段中输入相同的内容:“foobar” 在这里,确认密码字段仍然无效,直到密码字段失去焦点... 有没有办法强制在 keyup 事件上运行 matchingPassword 验证,而不是现在的工作方式?

【问题讨论】:

    标签: validation angular angular2-formbuilder


    【解决方案1】:

    你需要一个else 块:

    if (password.value !== passwordConfirmation.value) {
        passwordConfirmation.setErrors({mismatchedPasswords: true})
    }
    else {
        passwordConfirmation.setErrors(null);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-30
      • 2017-02-16
      • 2018-02-03
      相关资源
      最近更新 更多