无法使用angularJS2验证确认密码

时间:2017-02-01 12:56:29

标签: angular

我想检查密码输入是否与使用angularJS2的确认密码文本匹配,但我无法验证它。 以下是我的代码

 this.userForm = this.fb.group({
            'username': [this.users.username, [
                Validators.required,
                Validators.minLength(4),
                Validators.maxLength(24)
            ]
            ],
            'gender': [this.users.username, [Validators.required]],
            'password': [this.users.password, [Validators.required]],
            'confirmPassword': [this.users.password, Validators.required]
        }, { validation: this.matchingPasswords('password', 'confirmPassword') });

 matchingPasswords(passwordKey: string, confirmPasswordKey: string) {
        return (group: FormGroup): { [key: string]: any } => {
            let password = group.controls[passwordKey];
            let confirmPassword = group.controls[confirmPasswordKey];
            if (password.value !== confirmPassword.value) {
                return {
                    mismatchedPasswords: true
                };
            }
        }
    }

我已经浏览了各种文档,根据文档,当我们访问密码或确认密码元素时,函数 mismatchedPasswords 被调用,但在我的代码中,此方法未被调用。我错过了什么吗?

我已包含以下文件

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

1 个答案:

答案 0 :(得分:1)

为自定义验证创建一个新类,如下所示

      export class ValidationService {
      static getValidatorErrorMessage(validatorName: string, validatorValue?: any) {
      let config = {
      'mismatch': 'Password Mismatch.',
    };
      return config[validatorName];
    }
static comparePassword(control) {
    if (control.value) {
      if (control.root.get('passwordKey').value != control.root.get('confirmPasswordKey').value)
        return {'mismatch': true};
    }
  }

}

以下是您更新的表单组

import {ValidationService} from "point to yourlocation/validation.service";
  this.userForm = this.fb.group({
  'username': [this.users.username, [
    Validators.required,
    Validators.minLength(4),
    Validators.maxLength(24)
  ]
  ],
  'gender': [this.users.username, [Validators.required]],
  'password': [this.users.password, [Validators.required]],
  'confirmPassword': [this.users.password, [Validators.required, ValidationService.passwordValidator]]
})

以下是验证错误,将其放在需要显示错误的位置

<md-hint align="start">
  <control-messages [control]="userForm .get('confirmPassword')"></control-messages>
</md-hint>

最后,下面是根据返回类型

获取错误消息的组件
   import { Component, Input } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import {ValidationService} from " poin to ur location/validation.service";

@Component({
  selector: 'control-messages',
  template: `<div class="field-error" *ngIf="errorMessage !== null">{{errorMessage}}</div>`
})
export class ValidationComponent {
  @Input() control: FormControl;
  constructor() { }

  get errorMessage() {
    for (let propertyName in this.control.errors) {
      if (this.control.errors.hasOwnProperty(propertyName) && (this.control.dirty || this.control.touched)) {
        return ValidationService.getValidatorErrorMessage(propertyName, this.control.errors[propertyName]);
      }
    }
    return null;
  }
}