How to get error from custom validator in html?

I have such form in 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'
      }
      ]
    });

Validator code:

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>

So, it gives me a compile error: "Property 'incorrectPassword' does not exist on type 'ValidatorsModel'."

I understand that, but how can i touch this error in html? Are there any variants except writing specific directive for custom validators and work with it?

Upvotes: 0

Views: 282

Answers (1)

Meet
Meet

Reputation: 345

Ts Code

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 Code

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

Form Change:

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

Upvotes: 1

Related Questions