角度js触发多个验证器?

时间:2019-01-29 14:36:52

标签: angularjs typescript

嗨,我有一些验证器以我的角度形式出现。这就是它的样子。我正在使用Validators.compose添加一些自定义验证器。验证器错误然后显示在html组件上。在我的情况下,我想实现的是matchingValidator抛出错误时,我不希望Angular执行其他两个验证器。

this.formGroup = this.fb.group(
      {
        password: ['', [Validators.required, Validators.minLength(8)]],
        confirmPassword: ['', [Validators.required, Validators.minLength(8)]]
      },
      {
        validator: Validators.compose([
          matchingValidator('password', 'confirmPassword'),
          passwordStrengthValidator('password', 'confirmPassword'),
          blacklistedPasswordValidator(
            'password',
            'confirmPassword',
            this.blacklistedPasswords
          )
        ])
      }
    );

验证器代码如下

export function matchingValidator(
  passwordControlName = 'password',
  passwordConfirmControlName = 'passwordConfirm'
): ValidatorFn {
  return (formGroup: FormGroup): ValidationErrors => {
    const passwordValue: string = formGroup.get(passwordControlName).value;
    const passwordConfirmValue: string = formGroup.get(
      passwordConfirmControlName
    ).value;

    if (passwordValue.length && passwordConfirmValue.length) {
      return passwordValue !== passwordConfirmValue
        ? { passwordConfirmation: true }
        : null;
    }

    return null;
  };
}
export function passwordStrengthValidator(
  passwordControlName = 'password',
  passwordConfirmControlName = 'passwordConfirm'
): ValidatorFn {
  return (formGroup: FormGroup): ValidationErrors => {
    const passwordValue: string = formGroup.get(passwordControlName).value;
    const passwordConfirmValue: string = formGroup.get(
      passwordConfirmControlName
    ).value;

    if (
      passwordValue &&
      passwordConfirmValue &&
      passwordValue.localeCompare(passwordConfirmValue) === 0 &&
      passwordValue.length >= 8
    ) {
      if (
        !/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/.test(
          passwordValue
        )
      ) {
        return { invalidPasswordStrength: true };
      }
    }
    return null;
  };
}

export function blacklistedPasswordValidator(
  passwordControlName = 'password',
  passwordConfirmControlName = 'passwordConfirm',
  blacklistedPasswords: string[]
): ValidatorFn {
  return (formGroup: FormGroup): ValidationErrors => {
    const passwordValue: string = formGroup.get(passwordControlName).value;
    const passwordConfirmValue: string = formGroup.get(
      passwordConfirmControlName
    ).value;
    if (
      passwordValue &&
      passwordConfirmValue &&
      passwordValue.localeCompare(passwordConfirmValue) === 0 &&
      passwordValue.length >= 8
    ) {
      let found = false;
      found = blacklistedPasswords.some(element => element === passwordValue);

      if (found) {
        return { blacklistedPassword: true };
      }
    }
    return null;
  };

我的html代码如下。

 <alert type="danger" dismissable="false" *ngIf="formGroup.hasError('passwordConfirmation')">
        {{ 'VALIDATION.ERRORS.MATCHING_PASSWORDS' | translate }}
      </alert>

      <alert type="danger" dismissable="false" *ngIf="formGroup.hasError('invalidPasswordStrength')">
        {{ 'VALIDATION.ERRORS.PASSWORD_STRENGTH_INVALID' | translate }}
      </alert>

      <alert type="danger" dismissable="false" *ngIf="formGroup.hasError('blacklistedPassword')">
        {{ 'VALIDATION.ERRORS.PASSWORD_NOT_PERMITTED' | translate }}
      </alert>

所以简而言之,如果formGroup.hasError('passwordConfirmation')为true,我想要的是我想停止打印来自其他两个验证器的验证错误。 我怎样才能做到这一点。感谢我对angular js和打字稿不熟悉的任何帮助。

1 个答案:

答案 0 :(得分:0)

只要让您的检查更聪明:

<alert type="danger" dismissable="false" *ngIf="formGroup.hasError('passwordConfirmation') && !(formGroup.hasError('invalidPasswordStrength') || formGroup.hasError('blacklistedPassword'))">
    {{ 'VALIDATION.ERRORS.MATCHING_PASSWORDS' | translate }}
  </alert>

我在上面显示了一个示例,但在此要小心。如果所有三个都是正确的,那么您将不会显示任何错误。我建议只检查除一种可能的错误类型以外的所有其他错误,以防止出现该问题。

仅供参考,在输入see the docs上使用formControlName可以更轻松地解决错误。