代码之家  ›  专栏  ›  技术社区  ›  Sujay U N

Angular 6在不使用反应式表单的情况下验证确认密码

  •  0
  • Sujay U N  · 技术社区  · 6 年前

    我只需要比较密码并验证确认密码字段。 当密码不匹配时,我需要显示消息并显示错误:密码不匹配 当显示错误时,我需要设置无效的输入字段,从而禁用按钮。

    <form name="SignUpForm" #SignUpForm="ngForm"><br>
        <label><i class="fa fa-key"></i>
            <input type="password" name="Pwd" placeholder="Password" required pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,}"
             [(ngModel)]="SignUpNgsForm.Pwd" #Pwd="ngModel">
        </label>
            <div *ngIf="(Pwd.touched || Pwd.dirty) && Pwd.invalid" class="ErrorCls">
                <span *ngIf="Pwd.errors.required">Password is required.</span>
                <span *ngIf="Pwd.errors.pattern">Enter Strong password.</span><br>
            </div><br>
    
        <label><i class="fa fa-key"></i>
            <input type="password" name="RptPwd" placeholder="Repeat-Password" required pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,}"
             [(ngModel)]="SignUpNgsForm.RptPwd" #RptPwd="ngModel">
        </label>
            <div *ngIf="(RptPwd.touched || RptPwd.dirty) && RptPwd.invalid" class="ErrorCls">
                <span *ngIf="RptPwd.errors.required && RptPwd.invalid">Repeat-Password is required.</span>
                <span *ngIf="RptPwd.errors.pattern">Enter Strong password.</span>
            </div>
            <div *ngIf="(RptPwd.touched || RptPwd.dirty)" class="ErrorCls">
                <span *ngIf="!RptPwd.errors && SignUpNgsForm.Pwd != SignUpNgsForm.RptPwd">Passwords do not match</span>
            </div><br>
    
        <button [disabled]="!SignUpForm.form.valid" (click)="SignUp(SignUpForm)">Sign Up</button>
    </form>
    

    也尝试过:

    加载项组件.html

    <div *ngIf="(RptPwd.touched || RptPwd.dirty)" class="ErrCls">
        <span *ngIf="CheckMatchPassword(RptPwd)">Passwords do not match</span>
    </div><br>
    

    加载项组件.ts

    CheckMatchPassword(RptPwd)
    {
        if(!RptPwd.errors && this.SignUpNgsForm.Pwd != this.SignUpNgsForm.RptPwd)
        {
            return RptPwd.control.setErrors({'mismatch': true});
        }
        else
        {
    
            return RptPwd.control.setErrors(null);
        }
    }
    

    为此,我得到错误:

    错误错误:ExpressionChangedAfterithasbeencheckedderror:表达式在检查后已更改。上一个值:“ngif:false”。当前值:“ngif:true”。

    如果不使用formcontrol或reactive form,我该如何获得它?

    1 回复  |  直到 6 年前
        1
  •  1
  •   dockleryxk    6 年前

    我最近遇到了这个问题,所以我创建了一个验证器来处理这个问题。作为注释,我依赖于lodash,但我只是使用它来删除非唯一和空值。

    指令代码:

    import { Directive, forwardRef, Input } from '@angular/core';
    import { NG_VALIDATORS, Validator, FormGroup, ValidationErrors } from '@angular/forms';
    import * as _ from 'lodash';
    
    @Directive({
      selector: '[pugMatchValidator]',
      providers: [
        { provide: NG_VALIDATORS, useExisting: forwardRef(() => MatchValidatorDirective), multi: true }
      ]
    })
    export class MatchValidatorDirective implements Validator {
    
      // an array of the names of form controls to check
      @Input('pugMatchValidator') controlsToMatch: string[];
    
      constructor() { }
    
      validate(formGroup: FormGroup): ValidationErrors | null {
        let values = [];
        if (this.controlsToMatch) {
          for (let controlName of this.controlsToMatch) {
            const control = formGroup.controls[controlName];
            if (control && (control.touched || control.dirty)) {
              values.push(control.value);
            }
          }
    
          // compact removes empty and null values
          // uniq gets rid of duplicate fields, so one value should remain if everything matches
          values = _.uniq(_.compact(values));
    
          if (values.length > 1) {
            return { unMatchedFields: true };
          }
        }
        return null;
      }
    
    }
    

    接下来,只需传入要检查的控件数组:

    <form name="SignUpForm" #SignUpForm="ngForm" [pugMatchValidator]="['Pwd', 'RptPwd']">
    

    最后,您可以检查您的表单是否有效 SignUpForm.valid

    编辑: 在您的情况下,要显示错误,您将使用如下方法:

    <div *ngIf="SignUpForm.errors?.unMatchedFields && (RptPwd.touched || RptPwd.dirty)" class="ErrCls">
        Passwords do not match
    </div>
    
    推荐文章