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.

RequiredValidator

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.

  • 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 −

Validation

If you enter text in the textbox, then it is validated and the output is shown below −

Validations

PatternValidator

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 −

PatternValidator

PatternValidators

Similarly, you can try yourself to perform other types of validators.

Advertisements