Introduction
In every Angular application, there are multiple components where we need common tasks related to validating forms, such as:
- Having regex expressions that are used in inputs across the app.
- Matching two form fields, like password and confirm password.
- Displaying form error messages.
Writing code to get the message in every component is time-consuming. In this article, we will learn about creating a common validation service to help validate a reactive form and display form error messages.
There are two types of forms in Angular: Template Driven Forms and Reactive Forms. Today, we will focus on Reactive forms.
Reactive Form Validation
Reactive forms are also known as model-driven forms. This means that the HTML content changes depending on the code in the component. In reactive forms, we add validator functions directly to the form control model in the component class. Angular then calls these functions whenever the value of the control changes.
Advantages of using Reactive Forms:
- It's easier to write unit tests in reactive forms.
- It's easier to handle validation in reactive forms
Disadvantage of using Reactive Forms:
- It requires more coding implementation in the component
Here, we will focus on this disadvantage and write a common ValidationService so that we require less code in the component.
Step 1 - Setup
Create the Angular App.
Install Bootstrap and import the css in style.css
- @import '~bootstrap/dist/css/bootstrap.min.css'
Import ReactiveFormsModule in app.module.ts
- import {ReactiveFormsModule} from '@angular/forms'
-
- @NgModule({
- imports: [
- ...
- ReactiveFormsModule
- ]
-
- export class AppModule { }
Step 2 - Create Validation Service.
- @Injectable({
- providedIn: 'root'
- })
- export class ValidationService {
- constructor() { }
- }
We will add one object and three functions to this service.
Regex Object
Various Form Inputs have regex validation which we can use by Validators.pattern(). There can be multiple components that are using the same regex pattern. Therefore, we will add an object to have all regex values in a single place.
- public regex =
- {
- email: '^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$' ,
- pin : '^[0-9]{6}$'
- }
Function to Validate Matching of Input and Confirm Input fields
There are many times when we want to match 2 form inputs, like Password and Confirm Password or AccountNo and ConfirmAccountNo. To do that, we have added a common function named matchConfirmItems() where we can pass the formControl Names that need to be matched. This function will make the Confirm field invalid if the items do not match.
- matchConfirmItems(controlName: string, confirmControlName: string) {
- return (formGroup: FormGroup) => {
- const control = formGroup.controls[controlName];
- const confirmControl = formGroup.controls[confirmControlName];
- if (!control || !confirmControl) {
- return null;
- }
- if (confirmControl.errors && !confirmControl.errors.mismatch) {
- return null;
- }
- if (control.value !== confirmControl.value) {
- confirmControl.setErrors({ mismatch: true });
- } else {
- confirmControl.setErrors(null);
- }
- }
- }
Getting Validation Errors
Every form input can have some error we want to display. To get the error for all the inputs at a time we have added a function in the validation service so that we don't have to write it in all components.
Here, we will pass the formGroup and validationMessages Object from the component. The sample validationMessages object is added in the next step.
- getValidationErrors(group: FormGroup, validationMessages: Object): any {
- var formErrors = {};
-
- Object.keys(group.controls).forEach((key: string) => {
- const abstractControl = group.get(key);
-
- formErrors[key] = '';
- if (abstractControl && !abstractControl.valid &&
- (abstractControl.touched || abstractControl.dirty)) {
-
- const messages = validationMessages[key];
-
- for (const errorKey in abstractControl.errors) {
- if (errorKey) {
- formErrors[key] += messages[errorKey] + ' ';
- }
- }
- }
-
- if (abstractControl instanceof FormGroup) {
- let groupError = this.getValidationErrors(abstractControl, validationMessages);
- formErrors = { ...formErrors, ...groupError }
- }
- });
- return formErrors
- }
Source code of the complete validation service:
Step 3 - Add the component
Design the form using formgroup and formBuilder.
- constructor(private fb: FormBuilder, private _validation: ValidationService) {}
- this.signUpForm = this.fb.group({
- Name: ['', [Validators.required]],
- Email: ['', [Validators.required, Validators.pattern(this._validation.regex.email)]],
- Password: ['', [Validators.required]],
- ConfirmPassword: ['', [Validators.required]],
- },
- {
- validator: this._validation.matchConfirmItems('Password', 'ConfirmPassword'),
- });
There are different types of default validations we can use, like required validation, minlength validation, maxlength validation and pattern matching validation etc.
In the above formGroup, there are three types of validation,
- Validators.required
This is a built-in validation type we have attached to 'Name', 'Password' and 'Confirm Password' formControl.
- Validators.pattern
This is also a built-in validation type where we can add a regex pattern. Now inputs like email, phone, etc can be used in multiple forms. Therefore in the validationService we have added an object for all validation regex. We have attached it to the 'Email' formControl.
- Password and Confirm Password Match
We have added validator to the formgroup and passed formControlName 'Password' and 'ConfirmPassword' to matchConFirmItems function of Validation Service. This will make the formControl 'ConfirmPassword' invalid when both of these do not match.
Create an object to store the validation messages for each form control.
- validationMessages = {
- 'Name': {
- 'required': 'Name is required.',
- },
- 'Email': {
- 'required': 'Email is required.',
- 'pattern': 'Please provide valid Email ID'
- },
- 'Password': {
- 'required': 'Password is required.'
- },
- 'ConfirmPassword': {
- 'required': 'Confirm Password is required.',
- 'mismatch': 'Password and Confirm Password do not match'
- }
- };
Create an object to store the form validation error and update it whenever any form input is changed.
- formErrors = {};
- ngOnInit(){
- this.signUpForm.valueChanges.subscribe(
- value => {
- this.logValidationErrors()
- }
- );
- }
- logValidationErrors() {
- this.formErrors = this._validation.getValidationErrors(this.signUpForm, this.validationMessages);
- }
We will display the validation errors in the template. We will also call the logValidationErrors() on blur of each input.
- <form [formGroup]="signUpForm" (ngSubmit)="onSubmit()">
- <div class="form-group">
- <label>Name:</label>
- <input type="text" class="form-control" formControlName="Name" (blur)="logValidationErrors()">
- <span class="text-danger" *ngIf="formErrors.Name">
- {{formErrors.Name}}
- </span>
- </div>
- <div class="form-group">
- <label>Email:</label>
- <input type="text" class="form-control" formControlName="Email" (blur)="logValidationErrors()">
- <span class="text-danger" *ngIf="formErrors.Email">
- {{formErrors.Email}}
- </span>
- </div>
- <div class="form-group">
- <label>Password:</label>
- <input type="text" class="form-control" formControlName="Password" (blur)="logValidationErrors()">
- <span class="text-danger" *ngIf="formErrors.Password">
- {{formErrors.Password}}
- </span>
- </div>
- <div class="form-group">
- <label>ConfirmPassword:</label>
- <input type="text" class="form-control" formControlName="ConfirmPassword" (blur)="logValidationErrors()">
- <span class="text-danger" *ngIf="formErrors.ConfirmPassword">
- {{formErrors.ConfirmPassword}}
- </span>
- </div>
- <div class="row">
- <div class="col-md-12">
- <button type="submit" class="btn btn-success" [disabled]="!signUpForm.valid">Submit</button>
- </div>
- </div>
- </form>