Monday, 14 September 2020

Angular Reactive Forms: How to display an error+red border?

I'm starting to use Angular Reactive Forms.

I really like the idea of being able to have async validator(for things that have to check something against the DB), and I like the idea that the GUI doesn't need to know every rule.

So I've a dummy 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)]
    )),
  });

and the matching view:

       <form class="ion-margin" [formGroup]="loginForm" (ngSubmit)="login()">
        <ion-item lines="none">
          <ion-label position="floating">Email</ion-label>
          <ion-input type="text" formControlName="email"></ion-input>
        </ion-item>

        <ion-item lines="none">
          <ion-label position="floating">Password</ion-label>
          <ion-input type="password"  formControlName="password"></ion-input>
        </ion-item>

        <ion-row class="ion-margin">
          <ion-button type="submit" color="success" expand="block" [disabled]="loginForm.dirty && !loginForm.valid">Sign in</ion-button>
        </ion-row>
      </form>

Currently, I've no visual clue why the user cannot submit the form. Previously I was doing some ASP.Net Core projects, and there was the same kind of approach to have the model and its validations rules declared on the ViewModel/Controller side.

  1. I was kind of expecting that since the ion-input knows its form control name, it would at least be possible to automatically add some kind of red border if the validation fails. Is it normal? Did I miss something?
  2. Is there a way to provide the error message from the .ts file? I mean, it's kind of weird that the ViewModel AND the View has to know about each error(and its parameters(like minlength)) Would it not be the responsability of the Validator to provide an error if one?
  3. What if I've some global errors(like, the combination of username-password is invalid, can I use the form to give this information, or should I manage this elsewhere?

Sorry for the 3 questions in one, but it was with the same example and very close.



from Angular Reactive Forms: How to display an error+red border?

No comments:

Post a Comment