Reactive Form Validation In Angular.

Rajesh Roy
3 min readApr 14, 2021
Reactive Form Validation In Angular.

What Is Form Validation?

Form validation is a process to check where the information provided by the user is met our requirements or not.That is provided data is in right format or not. Before Submitting to the server,it is important to ensure all required form fields are filled out in correct format.This article leads you through reactive form fields concepts and examples of form validation in Angular.

Template Driven Vs Reactive Forms.

In Angular we have two options to create a form, first one is Template driven form and second one is Reactive Form. These two comes in @angular/form library and have many control classes. Template-driven forms make use of the “FormsModule”, while reactive forms are based on “ReactiveFormsModule”.Template-driven forms are asynchronous in nature, whereas Reactive forms are mostly synchronous.Template driven form is Suitable for simple scenarios where as Reactive Form Handles any complex scenarios.

Introduction.

Angular is a full-fledged framework, has provided excellent support for validating user inputs and displaying validation messages. It has lots of commonly used built-in validators that we can take advantage of, or we can even write our custom validators. In this post, we will learn about validations in reactive forms in Angular. We will create a simple user registration form and implement some inbuilt validations on it. Along with the inbuilt validations, we will also implement some custom validations to the reactive form.

We will perform the following custom validations for this registration form.

- Name should be in character and space only.

- Email id should be in proper format.

- Mobile no should be number only.

- Password and Confirm Password should be matched.

Create the Angular app.

ng new angular-form-validation

Change directories to the newly created project and open the project in VS Code using the set of command shown below.

cd angular-forms-validation

code.

Generate Registration component.

ng g c registration



Update app-routing.module.ts file.

Update app-routing.module.ts file to create route for registration component.

import { NgModule } from ‘@angular/core’;

import { Routes, RouterModule } from ‘@angular/router’;

import { RegistrationComponent } from ‘./login.component’;
const routes: Routes = ;
@NgModule({

imports: ,

exports:

})

export class AppRoutingModule { }

Add Below code in registration.component.html.

Reactive Form Validation In Angular.

First Name

First Name is required

First Name not valid.

Last Name

Last Name is required

Last Name not valid.

Email

Email is required

Mobile Number

Mobile no is required

Invalid Mobile No.

Gender

Male

FeMalem



Gender is required

Hobbies

Playing

Singigng
Dancing



Hobbies is required

Password

Password is required

Password must be at least 6 characters

Confirm Password

Confirm Password is required

Confirm Password must be at least 6 characters

Passwords must match

Date of birth

Date of birth is required

Select Image

Image is required






Register

Add below code on registration.component.ts.

import { Component, OnInit } from ‘@angular/core’;

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

import { ConfirmedValidator } from ‘../../helpers/confirmed.validator’;

import { Router } from “@angular/router”;
@Component({

selector: ‘app-registration’,

templateUrl: ‘./registration.component.html’,

styleUrls:

})

export class RegistrationComponent implements OnInit {
registerForm!: FormGroup;

submitted = false;

private readonly name_pattern = ‘^+$’;

private readonly email_pattern = “^+@+.{2,4}$”;

private readonly mobile_pattern = “^{9}$”;
constructor(private formBuilder: FormBuilder,private router: Router) { }
ngOnInit() {
this.registerForm = this.formBuilder.group({

firstName: ],

lastName: ],

email: ],

mobileno: ],

password: ],

confirmPassword: ],

gender:],

hobbies:,

dob:,

image:

},

{ validator: ConfirmedValidator(‘password’, ‘confirmPassword’) }

);
}
get f() { return this.registerForm.controls; }



submitted_data:any=
onSubmit() {

this.submitted = true;
// stop here if form is invalid

if (this.registerForm.invalid) {

return;

}



console.log(‘SUCCESS!! :-)nn’ + JSON.stringify(this.registerForm.value))

}
}

In the above component we define the form fields and validators for our registration form using an Angular FormBuilder to create an instance of a FormGroup that is stored in the registerForm property. Getter f is a convenience property to make it easier to access form controls from the template.

Create Confirmed Validator .

In this step we will create confirmed validator to check whether the password and confirm password is same or not in helpers folder. So add below code in confirmed.validator file.

import { FormGroup } from ‘@angular/forms’;
// custom validator to check that two fields match

export function ConfirmedValidator(controlName: string, matchingControlName: string){

return (formGroup: FormGroup) => {

const control = formGroup.controls;

const matchingControl = formGroup.controls;

if (matchingControl.errors && !matchingControl.errors.confirmedValidator) {

return;

}

if (control.value !== matchingControl.value) {

matchingControl.setErrors({ confirmedValidator: true });

} else {

matchingControl.setErrors(null);

}

}

}

--

--

Rajesh Roy

Web Developer having total 5 years experience in PHP, Codeigniter,Laravel,MySql,PostgreSql,Ajax,Javascript,Jquery,VueJs and Angular.