1

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

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

6 Comments

Error showing like Cannot read the property 'controls' in browser!
have you created like this in your component? myForm = new FormGroup({ firstname: new FormControl(), lastname: new FormControl()})
@SelvaKumarDuraisamy I edited answer check it now. i was given addEntryForm instead myForm. now can you check
Now its displaying Form, but When i clicked the first_name and release there is no showing any error message!!
error shows "Cannot find control with name : firstname "
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.