Angular:使用参数进行自定义验证

问题描述 投票:0回答:1

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

 //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>

enter image description here

angular typescript angular-reactive-forms
1个回答
1
投票

选项1 - 通过password验证verifyPasswordFormGroup

以下是确认密码验证的简单示例代码,您需要将验证器传递给包含控件FormGrouppasswordconfirmPassword

  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

选项2 - 使用功能匹配密码。

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

Component ts

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

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

© www.soinside.com 2019 - 2024. All rights reserved.