1

我在角度 7 上工作

我比较旧密码和新密码

如果两个都相同,则必须显示错误

但在我的情况下,旧密码和新密码相同但不显示错误

为什么不显示错误以及如何解决此问题?

当新旧值相同但不显示错误时,函数 CompareOldWithNew 返回 false

更改密码.ts

 oldPassword = new FormControl('', [Validators.required, Validators.minLength(6), Validators.maxLength(10)]);
 newPass = new FormControl('', [Validators.required, Validators.minLength(6), Validators.maxLength(10),this.CompareOldWithNew("oldPassword")]);
  ngOnInit() {
    this.createFormResetPassword();
  }
  get c() { return this.ChangePasswordForm.controls; }

CompareOldWithNew(field_name): ValidatorFn {

    return (control: AbstractControl): { [key: string]: any } => {

      const input = control.value;
      const isnotequalValues = control.root.value[field_name] != input;
      return  isnotequalValues ? null :{'old password must not match New': {isnotequalValues}} ;

    };
  }
  createFormResetPassword() {
    this.ChangePasswordForm = this.formBuilder.group({
 oldPassword: this.oldPassword,
      newPass: this.newPass
})
}
onSubmit() {

    if (this.ChangePasswordForm.invalid) {
        return;
    }

changpaassword.html

<div class="form-group">
  <label >OldPassword</label><br>
  <input type="password" formControlName="oldPassword" class="textboxclass"   [ngClass]="{ 'is-invalid': submitted && c.oldPassword.errors }" />
  <div *ngIf="submitted && c.oldPassword.errors" class="invalid-feedback">
      <div *ngIf="c.oldPassword.errors.required">Password is required</div>
      <div *ngIf="c.oldPassword.errors.minlength">Password must be at least 6 characters</div>
  </div>
</div>

<div class="form-group">
  <label>New Password</label><br>
  <input type="password" formControlName="newPass" class="textboxclass"    [ngClass]="{ 'is-invalid': submitted && c.newPass.errors }" />
  <div *ngIf="submitted && c.newPass.errors" class="invalid-feedback">
      <div *ngIf="c.newPass.errors.required">Password is required</div>
      <div *ngIf="c.newPass.errors.minlength">Password must be at least 6 characters</div>
      <div *ngIf="c.newPass.errors.CompareOldWithNew">old password not match new </div>
  </div>
</div>
4

1 回答 1

2

这将检查不相等的输入

new FormControl('', notEqual('xxx'))

验证器

import { AbstractControl, Validators, ValidatorFn } from '@angular/forms';

import { isPresent } from '../util/lang';

export const notEqual = (val: any): ValidatorFn => {
  return (control: AbstractControl): {[key: string]: boolean} => {
    if (isPresent(Validators.required(control))) return null;

    let v: any = control.value;

    return val !== v ? null : {notEqual: true};
  };
};
于 2020-01-13T12:29:40.570 回答