Angular2:确认密码的模型驱动表单验证

时间:2016-09-28 15:23:23

标签: validation angular angular2-forms angular2-formbuilder

我们如何使用angular2验证进行密码确认?我正在使用角度2.0决赛。

我正在使用formbuilder类进行模型驱动,如下所示:



    this.myForm = this.fb.group({
      name: ['', Validators.compose([Validators.required])],
      email: [''],
      passwordgroup: this.fb.group({
        password: ['', Validators.compose([Validators.required])],
        confirm_password: ['', Validators.compose([])]
      })
    });
  




2 个答案:

答案 0 :(得分:3)

您可以通过将此功能添加到您的组件来简单地使用自定义验证器

 import { AbstractControl } from '@angular/forms';

    function passwordConfirming(c: AbstractControl) {
        return c.get('password').value === c.get(' confirm_password').value

this.myForm = this.fb.group({
      name: ['', Validators.compose([Validators.required])],
      email: [''],
      passwordgroup: this.fb.group({
        password: ['', Validators.compose([Validators.required])],
        confirm_password: ['', Validators.compose([])]
      },  { validator: passwordConfirming })
    });

答案 1 :(得分:1)

this.myForm = this.fb.group({
      name: ['', Validators.compose([Validators.required])],
      email: [''],
      passwordgroup: this.fb.group({
        password: ['', Validators.compose([Validators.required])],
        confirm_password: ['', Validators.compose([])]
      },  passwordConfirming)
    });

删除上面的'validator'键(取消使用此对象表示法)并仅使用验证器名称'passwordConfirming'在没有语法错误的情况下工作。