validation - Angular 2 强制对 keyup 进行自定义验证

标签 validation angular angular2-formbuilder

我有这个代码:

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. 输入同样的东西,例如:“foo” enter image description here 到目前为止,没有问题。
  5. 在确认密码字段中输入不同的内容,例如:“foobar” (此时验证器显示这里有错误) enter image description here
  6. 点击密码字段
  7. 输入与密码字段相同的内容:“foobar” 而这里,确认密码字段仍然无效,直到密码字段失去焦点...... enter image description here 有没有办法强制在 keyup 事件上运行匹配密码验证,而不是现在如何工作?

最佳答案

你需要一个 else block :

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

关于validation - Angular 2 强制对 keyup 进行自定义验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42782820/

相关文章:

angular-reactive-forms - 如何清除 Angular Reactive Forms 中的 FormArray

validation - Angular 2 : how to apply custom validators in a certain order?

ruby-on-rails - rails : validating a field is present only if another is present

sql - 获取有效的日期范围。最小值和最大值

validation - 用于验证 csv 文件的已知服务

node.js - 从 API 响应中打开 PDF 到 Angular 中的新选项卡

angular - 在 Angular 中,我如何直接导航到延迟加载模块内的路径?

angular - 如何隐藏 Material 输入

angular - 如何以编程方式检查 formcontrol 在 Angular 中是否有效?

html - 如何使用 Selenium 测试是否为必填字段触发了 HTML5 验证?