Angular 8 - Form Validation

Form validation is an important part of web application. It is used to validate whether the user input is in correct format or not.
Let’s perform simple required field validation in angular.
Open command prompt and go to reactive-form-app.
cd /go/to/reactive-form-app
Replace the below code in test.component.ts file.
import { Component, OnInit } from '@angular/core';

//import validator and FormBuilder
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';

@Component({
   selector: 'app-test',
   templateUrl: './test.component.html',
   styleUrls: ['./test.component.css']
})

export class TestComponent implements OnInit {
   //Create FormGroup
   requiredForm: FormGroup;
   constructor(private fb: FormBuilder) {
      this.myForm();
   }

   //Create required field validator for name
   myForm() {
      this.requiredForm = this.fb.group({
      name: ['', Validators.required ]
      });
   }
   ngOnInit()
   {

   }
}
Here,
We have used form builder to handle all the validation. Constructor is used to create a form with the validation rules.
Add the below code inside test.component.html file.
<div>
   <h2>
     Required Field validation
   </h2>
   <form [formGroup]="requiredForm" novalidate>
         <div class="form-group">
           <label class="center-block">Name:
             <input class="form-control" formControlName="name">
           </label>
         </div>
         <div *ngIf="requiredForm.controls['name'].invalid && requiredForm.controls['name'].touched" class="alert alert-danger">
             <div *ngIf="requiredForm.controls['name'].errors.required">
             Name is required.
           </div>
         </div>
   </form>
 <p>Form value: {{ requiredForm.value | json }}</p>
 <p>Form status: {{ requiredForm.status | json }}</p>
 </div>
Here,
requiredForm is called global form group object. It is a parent element. Form controls are childrens of requiredForm.
requiredForm is called global form group object. It is a parent element. Form controls are childrens of requiredForm.
Conditional statement is used to check, if a user has touched the input field but not enter the values then, it displays the error message.
Conditional statement is used to check, if a user has touched the input field but not enter the values then, it displays the error message.
Finally, start your application (if not done already) using the below command −
ng serve
Now run your application and put focus on text box. Then, it will use show Name is required as shown below −
If you enter text in the textbox, then it is validated and the output is shown below −
PatternValidator is used to validate regex pattern. Let’s perform simple email validation.
Open command prompt and to reactive-form-app.
cd /go/to/reactive-form-app
Replace below code in test.component.ts file −
import { Component, OnInit } from '@angular/core';

import { FormGroup, FormControl, Validators, FormBuilder } from 
'@angular/forms';

@Component({
   selector: 'app-test',
   templateUrl: './test.component.html',
   styleUrls: ['./test.component.css']
})

export class TestComponent implements OnInit {
   requiredForm: FormGroup;
   constructor(private fb: FormBuilder) {
      this.myForm();
   }

   myForm() {
      this.requiredForm = this.fb.group({
      email: ['', [Validators.required, 
         Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$")] ]
      });
   }

   ngOnInit()
   {

   }
}
Here,
Added email pattern validator inside the Validator.
Update below code in test.component.html file −
<div>
   <h2>
   Pattern validation
   </h2>
   <form [formGroup]="requiredForm" novalidate>
   <div class="form-group">
      <label class="center-block">Email:
      <input class="form-control" formControlName="email">
      </label>
   </div>
   <div *ngIf="requiredForm.controls['email'].invalid && requiredForm.controls['email'].touched" class="alert alert-danger">
       <div *ngIf="requiredForm.controls['email'].errors.required">
      Email is required.
      </div>
   </div>
   </form>
   <p>Form value: {{ requiredForm.value | json }}</p>
   <p>Form status: {{ requiredForm.status | json }}</p>
</div>
Here, we have created the email control and called email validator.
Run your application and you could see the below result −
Similarly, you can try yourself to perform other types of validators.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page