Angular 6 Reactive Forms Validation Example
Welcome readers, in this tutorial, we will learn the basic of Reactive Forms in angular and perform custom validations on the form.
1. Introduction
In a web application, a form is a common approach that allows users to submit input and interact with the application. Frequently used for user login, information search, and feedback submission. The angular framework provides Template-driven and Reactive-driven forms to communicate with the users.
- The template-driven forms use the in-built directives (such as
ngModel
,ngModelGroup
, andngForm
) available in the Forms module - The reactive driven forms use the
FormControl
,FormGroup
, andFormBuilder
classes available in the Reactive Forms module- Offer predictability and synchronous access to the data model
- Offer reactive patterns, testing, and validation
To work with reactive forms, open the visual studio code and let us see how to implement this tutorial in angular 6 frameworks.
2. Angular 6 Reactive Forms Validation Example
Here is a systematic guide for implementing this tutorial.
2.1 Tools Used
We are using Visual Studio Code and Node Terminal to compile and execute the angular code on a browser.
2.2 Project Structure
In case you are confused about where you should create the corresponding files or folder, let us review the project structure of the angular application.
3. Creating Angular application
Run the ng new angular-reactive-form-custom-validations-assignment
command in the npm console to create a new angular project. Once the new project is created, following the below steps.
3.1 Import Reactive forms module
To start working with the reactive forms we will need to import the ReactiveFormsModule
module in src/app/app.module.ts
file.
app.module.ts
// Importing the reactive forms module. import { ReactiveFormsModule } from '@angular/forms'; // Declaring the reactive forms module in the imports section of NgModule decorator. imports: [ BrowserModule, ReactiveFormsModule ],
3.2 Building the Form Template
To create a form we will use the different reactive form property tags introduced in the angular framework. We will,
- Use the
formGroup
property to bind our form with a name (i.e.myform
). This will bind the form with aFormGroup
object declared in the component class - Use the
formControlName
property to bind the input fields to the individual form controls - Use the
ngSubmit
property to submit the form and display the values on successful validation
Add the following code the src/app/app.component.html
file.
app.component.html
<div class="container myWidth"> <div class="row"> <div class="col-md-6 offset-md-3"> <h2 class="text-center">{{ title }}</h2> <hr /> <form [formGroup]="myForm" (ngSubmit)="_formSubmit()"> <!-- EMAIL ADDRESS FIELD --> <div class="form-group"> <input type="text" formControlName="email" class="form-control" placeholder="Enter email" /> <div *ngIf="myForm.controls.email.invalid && myForm.controls.email.touched" class="text-danger"> <small *ngIf="myForm.controls.email.errors.required">Email address is required.</small> <small *ngIf="myForm.controls.email.errors.email">Email must be a valid email address.</small> </div> </div> <!-- PASSWORD FIELD --> <div class="form-group"> <input type="password" formControlName="pwd" class="form-control" placeholder="Enter password" /> <div *ngIf="myForm.controls.pwd.invalid && myForm.controls.pwd.touched" class="text-danger"> <small *ngIf="myForm.controls.pwd.errors.required">Password is required.</small> <small *ngIf="myForm.controls.pwd.errors.minlength">Password must be at least 6 characters.</small> </div> </div> <!-- CONFIRM PASSWORD FIELD --> <div class="form-group"> <input type="password" formControlName="cnfPwd" class="form-control" placeholder="Enter confirm password" /> <div *ngIf="myForm.controls.cnfPwd.invalid && myForm.controls.cnfPwd.touched" class="text-danger"> <small *ngIf="myForm.controls.cnfPwd.errors.required">Confirm password is required.</small> <small *ngIf="myForm.controls.cnfPwd.errors.mustMatch">Password & Confirm Password must match.</small> </div> </div> <!-- REGISTER BUTTON --> <div class="form-group"> <input type="submit" value="Register" [disabled]="myForm.invalid" class="btn btn-primary" /> </div> </form> </div> </div> </div>
3.3 Creating Custom Validation for Password property
In the custom validation class, we will match the password & confirm-password property and add the password mismatch validation. Add the following code the src/app/Passwordvalidation.ts
file
Passwordvalidation.ts
import { AbstractControl } from '@angular/forms'; export class Passwordmatch { // Custom validator to check that two fields match. static matchPassword(ac: AbstractControl) { const pwd = ac.get('pwd'); const cnfpwd = ac.get('cnfPwd'); if (pwd.value === cnfpwd.value) { return null; } ac.get('cnfPwd').setErrors({ mustMatch: true }); return true; } }
3.4 Initialize Form data and Validations
In the component class, we will initialize the form with default values and add some basic validations. In addition, we will define our form group, individual form controls within the form group, and the validator class to set the validation properties for each control. Add the following code the src/app/app.component.ts
file
app.component.ts
import { Component, OnInit } from '@angular/core'; // Importing the reactive form module classes. import { FormGroup, FormBuilder, Validators } from '@angular/forms'; // Import custom validator to validate that password and confirm password fields match. import { Passwordmatch } from './Passwordvalidation'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'Angular6 Reactive forms custom validation'; myForm: FormGroup; constructor(private fb: FormBuilder) { } _formValidate() { // Here we have used a form builder and an array to allow for multiple validation rules on a form. this.myForm = this.fb.group( { email: ['', Validators.compose([Validators.required, Validators.email])], pwd: ['', Validators.compose([Validators.required, Validators.minLength(6)])], cnfPwd: ['', Validators.required] }, { validator: Passwordmatch.matchPassword } ); } // To initialize the form group and validations in the 'ngOnInit' lifecycle hook. ngOnInit() { this._formValidate(); } // To show how developers can access the form control values. _formSubmit() { if (this.myForm.invalid) { return; } alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.myForm.getRawValue())); } }
4. Run the Application
As we are ready with all the changes, let us compile and run the angular application with ng serve
command. Once the projects are successfully compiled and deployed, open the browser to test it.
5. Project Demo
Open your favorite browser and hit the angular application url (http://localhost:4200/
) to display the index page of the application.
A user can enter the details and if the confirm password field does not match the password, an error is shown.
That is all for this tutorial and I hope the article served you whatever you were expecting for. Happy Learning and do not forget to share!
6. Conclusion
In this section, we learned how to create a simple form model, bind it to the HTML form using reactive form classes, and apply custom validations. Developers can download the sample application as an Eclipse project in the Downloads section.
7. Download the Eclipse Project
This was a tutorial of Custom Validations in Angular Reactive Form.
You can download the full source code of this example here: Angular 6 Reactive Forms Validation Example