How to retrieve arguments of Reactive Form validators in the template?

208 Views Asked by At

I've started to use ReactiveForms for my forms, but some things are bothering me. Amongst them is that if I want to display relevant error messages, I need to provide some information to the user to correct its error.

By example, if I've this login form:

 loginForm = this.formBuilder.group({
    email: new FormControl(
      '',
      Validators.compose([Validators.required, Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')])
    ),
    password: new FormControl('', Validators.compose([Validators.required, Validators.minLength(8)])),
  });

for the password, I need to give the user that the password has to be at least 8 char long.

I could definitely just hard code this in my error message:

  <div
    class="error-message alert alert-danger"
    *ngIf="loginForm.get('password').hasError('minLength')"  >
    <ion-text color="danger" class="text">
      <ion-icon class="icon" name="alert-outline"></ion-icon>
       Password has to be at least 8 characters long
    </ion-text>
  </div>

It would work, but the day I change this value in the model, you have to change it in the message. And worse, if it's localized, you have to update all the localization with the correct value.

So, how to retrieve, for example, the minLength value in my template? This has to be possible, right?

1

There are 1 best solutions below

0
On BEST ANSWER

Check the error writing

{{loginForm.get('password')?.errors|json}})

You'll see that is an object with requiredLength and actualLength, so you can write

Password has to be at least 
    {{loginForm.get('password')?.errors?.minlength.requiredLength}} 
             characters long