Angular: 带参数的自定义验证

Angular: Custom validation with parameter

我正在尝试使用 Angular 6 使用 Reactive Form 实现验证密码验证,但我无法获得最佳方法,下面是一个适用于“1234”的示例,但我想而是传递密码控件的值。 我尝试使用 ValidatePWD(this) 但也不起作用。

 //component.ts
 import { ValidatePWD } from './compare.validator';

 this.form = this._fb.group({
                  'user': ['', Validators.compose([Validators.required])],                       
                  'password': ['', Validators.compose([Validators.required])],
                  'verifypassword': ['', [Validators.required, ValidatePWD]],

 });


//compare.validator.ts
import { AbstractControl, FormGroup } from '@angular/forms';
export function ValidatePWD(control: AbstractControl ) {    
  if (control.value != "1234") {
    return { validPWD: true };
  }
  return null;
}


<div class="form-group">
      <label>Password: {{model.password}}</label>
      <input [(ngModel)]="model.password" [formControl]="password" class="form-control" type="password">
</div>

<div class="form-group">
     <label >Verify Password</label>
     <input[(ngModel)]="model.verifypassword" [formControl]="verifypassword"  class="form-control" type="password">
</div>

Option 1 - Validate the password and verifyPassword through FormGroup,

这是确认密码验证的简单示例代码,您需要将验证器传递给 FormGroup,其中包含控件 passwordconfirmPassword.

  this.form = this._fb.group({
              'user': ['', Validators.compose([Validators.required])],                       
              'password': ['', Validators.compose([Validators.required])],
              'verifypassword': ['', [Validators.required]],

  }, { validator: this.passwordMatchValidator });

  passwordMatchValidator(g: FormGroup) {
    return g.get('password').value === g.get('verifypassword').value
       ? null : {'mismatch': true};
  }

html

<div *ngIf="form.invalid && form.errors['mismatch']">Password did not match</div>

示例在这里 -https://stackblitz.com/edit/confirm-password-q3ngps

Option 2 - Use a function to match the password.

密码-validator.ts

export class PasswordValidation {

    static MatchPassword(AC: AbstractControl) {
        let password = AC.get('password').value;
        if(AC.get('confirmPassword').touched || AC.get('confirmPassword').dirty) {
            let verifyPassword = AC.get('confirmPassword').value;

            if(password != verifyPassword) {
                AC.get('confirmPassword').setErrors( {MatchPassword: true} )
            } else {
                return null
            }
        }
    }
}

组件 ts

this.form = this._fb.group({
      password: ['', Validators.required],
      confirmPassword: ['', Validators.required]
    }, {
      validator: PasswordValidation.MatchPassword
    });

工作副本在这里 - https://stackblitz.com/edit/material-password-confirm-pnnd4t