加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:36:13 所属栏目:安全 来源:网络整理
导读:我有这个代码: this.form = fb.group({ username: ['',Validators.compose([Validators.required])],fullName: ['',password: ['',confirmPassword: ['',Validators.required],},{validator: matchingPasswords('password','confirmPassword')}); matchingP
我有这个代码:

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

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

}

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>

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

>单击第一个密码字段.
>填写密码,例如:“foo”
>单击确认密码字段.
> tpye同样的事情,例如:“foo”

enter image description here


直到这一点,没有问题.
>在确认密码字段中键入不同的内容,例如:“foobar”
(此时,验证器显示此处存在错误)

enter image description here


>单击密码字段
>输入密码字段中的相同内容:“foobar”
在这里,确认密码字段仍然无效,直到密码字段失去焦点…

enter image description here


有没有办法,强制matchupPassword验证在keyup事件上运行,而不是现在如何工作?

解决方法

你需要一个else块:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读