Form Validation in Angular applications plays a very important role to provide a good and smooth user experience. In some situations, we may need to dynamically handle or adjust the validation rules for form controls as the user starts filling out the sections.
In this guide, we will discuss the process of how to set and reset the required validation on Angular form controls by using the Reactive approach. We will create a simple yet useful example to demonstrate the dynamic control validation riles within the Angular Reactive forms.
Dynamic Form Validation in Angular
In complex Angular applications, the management of user input through forms is very common task. These forms may have dynamically generated form controls which might require validation behaviour that may depend on various factors or simply the previously filled-out fields. For example, if a user selects the marital status as “Married,” you might need to enforce validation on the spouse’s name field.
Creating a Simple Reactive Form
Let’s start by creating a basic example of a Reactive Form with Angular. In the app.component.html
file, include the following code snippet:
<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
<label>
First Name:
<input type="text" formControlName="firstName">
</label>
<label>
Last Name:
<input type="text" formControlName="lastName">
</label>
<button type="submit">Submit</button>
</form>
<button (click)="setRequired()">Make Required</button>
<button (click)="unsetRequired()">Make Not Required</button>
Here, we have a simple form with two input fields for the first name and last name. Additionally, there are buttons to set and unset the “required” property for these form controls dynamically.
Updating the Component Class
In the component class, we will start by creating a dynamic form using Angular’s FormBuilder utility:
import { Component } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
profileForm = this.fb.group({
firstName: [''],
lastName: ['']
});
constructor(private fb: FormBuilder) {}
onSubmit() {
alert("IS FORM VALID? " + this.profileForm.valid);
}
setRequired() {
this.profileForm.controls.firstName.setValidators([Validators.required]);
this.profileForm.controls.lastName.setValidators([Validators.required]);
this.profileForm.controls.firstName.updateValueAndValidity();
this.profileForm.controls.lastName.updateValueAndValidity();
}
unsetRequired() {
this.profileForm.controls.firstName.setValidators(null);
this.profileForm.controls.lastName.setValidators(null);
this.profileForm.controls.firstName.updateValueAndValidity();
this.profileForm.controls.lastName.updateValueAndValidity();
}
}
In the above component class, we have defined the profileForm
using FormBuilder
. Also, we have implemented the onSubmit()
method to display whether the form is valid or not via alert.
Dynamically Updating Validation Rules
The functionality to set or remove required validation is happening in the setRequired()
and unsetRequired()
methods. These methods allow us to dynamically update the validation rules of form controls based on user interactions. Let’s have quick look into these methods:
setRequired()
setRequired() {
this.profileForm.controls.firstName.setValidators([Validators.required]);
this.profileForm.controls.lastName.setValidators([Validators.required]);
this.profileForm.controls.firstName.updateValueAndValidity();
this.profileForm.controls.lastName.updateValueAndValidity();
}
This method sets the “required” validation for both the first name and last name form controls. We have achieved this by calling the setValidators()
method on each control and passing an array containing the Validators.required
validator. The updateValueAndValidity()
method is then called to update the control’s validation status.
Similarly in the unsetRequied()
method, we are setting the setValidators with null to remove any existing required rules and then calling the updateValueAndValidity()
to update the control’s validation status accordingly.
unsetRequired()
unsetRequired() {
this.profileForm.controls.firstName.setValidators(null);
this.profileForm.controls.lastName.setValidators(null);
this.profileForm.controls.firstName.updateValueAndValidity();
this.profileForm.controls.lastName.updateValueAndValidity();
}
Conclusion
In this tutorial, we have discussed how to dynamically update form control validation in Angular Reactive Forms by utilizing the setValidators()
method and the updateValueAndValidity()
method. Using this way, we can easily adjust validation rules based on various conditions.
Leave a Reply