如何从 html 中的自定义验证器获取错误?

How to get error from custom validator in html?

我在ts中有这样的表格:

this._logInForm = _formBuilder.group<ILoginModel>({
      userName: ['', {
        validators: [Validators.required, Validators.maxLength(10)],
        updateOn: 'blur'
      }],
      password: ['', {
        validators: [PASSWORD_VALIDATOR(/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{5,}$/)],
        updateOn: 'blur'
      }
      ]
    });

验证码:

function PASSWORD_VALIDATOR(correctPattern: RegExp): ValidatorFn {
  return ((control: AbstractControl): { incorrectPassword: RegExp } | null => {
    if (!correctPattern.test(control.value)) {
      return { incorrectPassword: correctPattern };
    }
    return null;
  });
}

HTML:

<p class="login__validation-error" *ngIf="passwordControl.errors!.incorrectPassword && passwordControl.touched">Password must be longer than 5 symbols and must contain 1 digit, 1 lowercase and 1 uppercase letter</p>

所以,它给了我一个编译错误:“属性 'incorrectPassword' 在类型 'ValidatorsModel' 上不存在。”

我明白了,但是我怎样才能解决 html 中的这个错误?除了为自定义验证器编写特定指令并使用它之外,是否有任何变体?

TS代码

function PASSWORD_VALIDATOR(correctPattern: RegExp): ValidatorFn {
    return (control: FormControl) => {
    let urlRegEx: RegExp = new RegExp('/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{5,}$/');
       
        if (control.value && !control.value.match(urlRegEx)) {
            return {
                pattern: 'Password must be longer than 5 symbols and must contain 1 digit, 1 lowercase and 1 uppercase letter'
            };
        } else {
            return null;
        }
    }
};

Html代码

<p class="login__validation-error" *ngIf="_logInForm .controls['password'].errors.pattern">Password must be longer than 5 symbols and must contain 1 digit, 1 lowercase and 1 uppercase letter</p>

表单更改:

 password: ['', PASSWORD_VALIDATOR('password')], // password means formControlName