Skip to content Skip to sidebar Skip to footer

Angular 6 And Ionic 3 Reactive Form Validation Error Not Display

I am working on a project which uses the latest version of Angular and Ionic. I am working on a registration page. I need to display some error when the form input is not valid. I

Solution 1:

Try changing the condition as follows,

this.registrationForm = this.fb.group({
      userName: [
        null, Validators.compose([Validators.maxLength(30), Validators.pattern('^[a-zA-Z]+$'), Validators.required])
      ],

EDIT

Also change your template as follows,

<ion-item *ngIf="!registrationForm .controls.userName.valid && (registrationForm .controls.userName.dirty)"> <p>Please enter a valid name.</p> </ion-item> 

Solution 2:

You'll have to add the error message div outside the ion-item tag like this:

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-list class="items-middle" text-center>
    <form [formGroup]="registrationForm">
      <ion-item>
        <ion-label floating>Full Name</ion-label>
        <ion-input type="text" formControlName="userName"></ion-input>
      </ion-item>
      <div *ngIf="registrationForm.get('userName').touched && registrationForm.get('userName').invalid"> name is required</div>
      <ion-buttons padding-top>
        <button ion-button full round type="submit" [disabled]="!registrationForm.valid">SIGNUP</button>
      </ion-buttons>
    </form>
    <pre> {{registrationForm.status}}</pre>
    <pre> {{registrationForm.value | json }}</pre>
    <pre> {{registrationForm.get('userName').invalid | json }}</pre>
    <pre> {{registrationForm.get('userName').touched | json }}</pre>
  </ion-list>
</ion-content>

Also, you can simply use registrationForm.get('userName').touched && registrationForm.get('userName').invalid">

Here's a Sample StackBlitz.


Solution 3:

Add <span> tag with your formControl like this :

OR Add class="text-danger" in your current <div>.

.html file.

Display required Error Message

<span class="text-danger" *ngIf="registrationForm.controls['userName'].hasError('required') && (registrationForm.controls['userName'].dirty || registrationForm.controls['userName'].touched)">Field is required</span>

Display pattern Error Message

<span class="text-danger" *ngIf="registrationForm.controls['userName'].hasError('pattern') && (registrationForm.controls['userName'].dirty || registrationForm.controls['userName'].touched)">Enter valid username.</span>

ts file.

this.registrationForm = this.fb.group({
  'userName': [null, Validators.compose([Validators.pattern('^[a-zA-Z]+$'), Validators.required])]
});

Post a Comment for "Angular 6 And Ionic 3 Reactive Form Validation Error Not Display"