SelvaKumar Duraisamy
SelvaKumar Duraisamy

Reputation: 51

How to display validation error messages in Angular 2

I want to create a form where the user will enter his First_Name and Last_Name. I'd like to validate those fields in client-side.

Is there any generic forms validator in Angular 2 and also I want show the error message in client-side. How to show error messages ?

Bellow is my code

html file

<form [formGroup]="myForm"  (ngSubmit)="submit()" >
<ion-row>
  <ion-item>
    <ion-label primary floating>FIRST NAME</ion-label>
    <ion-input type="text" id="firstname" class="form-control" formControlName="firstname"></ion-input>
  </ion-item>

 <ion-item>
   <ion-label primary floating>LAST NAME</ion-label>
   <ion-input type="text" id="lastname"  class="form-control" formControlName="lastname" ></ion-input>
 </ion-item>
</ion-row>
</form>

ts file:

this.myForm = formBuilder.group({
   'firstname'  :  ['', Validators.compose([Validators.required, Validators.minLength(4), Validators.maxLength(10)])],
   'lastname'   :  ['', Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(10)])],})

Backend Endpoint name and fields name:

submit(){
    let registerNewUserObj ={
       first_name:this.myForm.value.firstname,
       last_name:this.myForm.value.lastname

Upvotes: 1

Views: 3887

Answers (1)

Amruth
Amruth

Reputation: 5912

Use this code to display error messages.

<ion-input type="text" id="firstname" class="form-control" formControlName="firstname"></ion-input>
<p class="errorMessage" *ngIf="myForm.controls.firstname.errors && myForm.controls.firstname.dirty ">Please provide first name.</p>

Upvotes: 1

Related Questions