Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic Validation - show error message like material

I've been working on a Login and Registration Page in Ionic 5. I wanted to display error messages below the input text field like here

enter image description here

So I implemented Angular Responsive Forms

  ngOnInit() {
    this.afAuth.authState.subscribe(data => console.log(data));

    this.myForm = this.fb.group({
      email: ['', [
        Validators.required,
        Validators.email
      ]],
      password: ['', [
        Validators.required,
        Validators.pattern('^(([a-zA-Z][^:.*/}{;])*\d*)$')
      ]]
    });
  }

  get email(){
    return this.myForm.get('email');
  }

  get password(){
    return this.myForm.get('password');
  }

After doing that, I created a form with two ion-input fields.

<ion-item class="input_item">
  <ion-label position="floating">E-Mail</ion-label>
  <ion-input formControlName="email" position="floating"></ion-input>
</ion-item>

<div class="validation-errors">
    <div class="error-message" *ngIf="email.errors && email.dirty || email.touched">
      Your E-Mail is invalid!
    </div>
</div>

I tried to use this class "validation-errors" but it didn't display the message the way I wanted. I managed to get it to look like this

enter image description here

But is there some easier way to display the error message the way Angular Material does it? Is there something from Ionic I can use, or do I have to implement Angular Material UI components?

Thanks for answering.

UPDATE: Since this question has been gaining some traction since my original post and there doesn't seem to be a simpler solution I wanted to post the used styles for anyone passing by:

.validation-errors {
    font-size: small;
    color: var(--ion-color-danger, #f1453d);
}

/* These are necessary to make the underline red */
ion-item.invalid {
    --highlight-background: var(--ion-color-danger, #f1453d);
}

ion-item {
    --highlight-color-invalid: var(--ion-color-primary);
}

with the inclusion of this in the template

<ion-item [class.invalid]="email.errors && email.touched">
like image 915
Lucas Engleder Avatar asked Apr 02 '20 10:04

Lucas Engleder


1 Answers

In Ionic 6, this is made awesomely simple by using the error slot on ion-item.

See the docs here https://ionicframework.com/docs/api/item#slots

Example:

<ion-item>
  <ion-label>Name</ion-label>
  <ion-input formControlName="firstName"></ion-input>
  <span slot="error">Name is required</span>
</ion-item>
like image 64
jiroch Avatar answered Nov 03 '22 05:11

jiroch