angular 8:反应式匹配密码 [英] angular 8: Reactive Form match password

查看:31
本文介绍了angular 8:反应式匹配密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 angular 项目中有这样定义的反应形式:

I have the reactive form in my angular project that defines like this:

this.createUserFormGroup = new FormGroup({
  'userName': new FormControl(null, [Validators.required, Validators.maxLength(256)]),
  'name': new FormControl(null, [Validators.required, Validators.maxLength(64)]),
  'roleNames': new FormArray([]),
  'password': new FormControl(null, [Validators.required, Validators.maxLength(32)]),
  'confirmPassword': new FormControl(null, [Validators.required])
});

如何查看密码和confirmPassword是否匹配?

how can I check the matching of password and confirmPassword?

推荐答案

您可以创建自定义验证器并在 FormGroup 中使用它,如

You can create a custom validator and use it in FormGroup like

    passwordConfirming(c: AbstractControl): { invalid: boolean } {
    if (c.get('password').value !== c.get('confirmPassword').value) {
        return {invalid: true};
    }
}

而且你需要像这样使用这个自定义验证器.

And you need to use this custom validator like.

 this.createUserFormGroup = new FormGroup({
  'userName': new FormControl(null, [Validators.required, Validators.maxLength(256)]),
  'name': new FormControl(null, [Validators.required, Validators.maxLength(64)]),
  'roleNames': new FormArray([]),
  'password': new FormControl(null, [Validators.required, Validators.maxLength(32)]),
  'confirmPassword': new FormControl(null, [Validators.required])
},{validator: this.passwordConfirming});

并像

 <span *ngIf="createUserFormGroup.errors?.invalid">
      Password doesn't match
  </span>

这篇关于angular 8:反应式匹配密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆