Purpose of Validators class in Angular
Last Updated :
10 May, 2024
The Validators class in Angular provides a set of built-in validation functions that can be used to validate form controls and user input. It is part of the @angular/forms module and is commonly used in conjunction with Angular's Reactive Forms or Template-driven Forms.
Prerequisites
Key Functions of Validators Class
The Validators class provides several static methods that return validation functions. These validation functions can be used to validate form controls based on different criteria, such as required fields, minimum and maximum values, pattern matching, and more.
Some of the commonly used validation functions provided by the Validators class include:
- required: Validates that the control value is not null or an empty string.
- minLength: Validates that the control value has a minimum length.
- maxLength: Validates that the control value does not exceed a maximum length.
- pattern: Validates that the control value matches a regular expression pattern.
- email: Validates that the control value is a valid email address.
- min: Validates that the control value is greater than or equal to a specified minimum value.
- max: Validates that the control value is less than or equal to a specified maximum value.
Features of Validator Class
The Validators class provides several benefits and features:
- Built-in Validation Functions: Angular comes with a set of built-in validation functions that cover many common validation scenarios, reducing the need to write custom validation logic.
- Reusable Validation Functions: The validation functions provided by the Validators class are reusable across different form controls and components.
- Composable Validation Functions: Multiple validation functions can be combined to create more complex validation rules using the Validators.compose function.
- Cross-Field Validation: Angular also supports cross-field validation, which allows you to validate multiple form controls based on their combined values.
Steps to implement Validators
Step 1: Set up a new Angular application
ng new my-app
cd validators-example
Folder Structure
folder structureDependencies
"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/platform-server": "^17.3.0",
"@angular/router": "^17.3.0",
"@angular/ssr": "^17.3.3",
"express": "^4.18.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}
Example
HTML
<!-- app.component.html -->
<form [formGroup]="userForm" (ngSubmit)="onSubmit()">
<div>
<label for="name">Name</label>
<input id="name" type="text" formControlName="name" />
<div *ngIf="name?.invalid && (name?.dirty || name?.touched)">
<div *ngIf="name?.errors?.['required']">Name is required.</div>
<div *ngIf="name?.errors?.['minlength']">
Name must be at least 3 characters long.
</div>
<div *ngIf="name?.errors?.['maxlength']">
Name cannot exceed 20 characters.
</div>
</div>
</div>
<div>
<label for="email">Email</label>
<input id="email" type="email" formControlName="email" />
<div *ngIf="email?.invalid && (email?.dirty || email?.touched)">
<div *ngIf="email?.errors?.['required']">Email is required.</div>
<div *ngIf="email?.errors?.['email']">Invalid email format.</div>
</div>
</div>
<div>
<label for="password">Password</label>
<input id="password" type="password" formControlName="password" />
<div *ngIf="password?.invalid && (password?.dirty || password?.touched)">
<div *ngIf="password?.errors?.['required']">Password is required.</div>
<div *ngIf="password?.errors?.['pattern']">
Password must contain at least one uppercase letter, one lowercase
letter, one digit, and one special character.
</div>
</div>
</div>
<div>
<label for="age">Age</label>
<input id="age" type="number" formControlName="age" />
<div *ngIf="age?.invalid && (age?.dirty || age?.touched)">
<div *ngIf="age?.errors?.['required']">Age is required.</div>
<div *ngIf="age?.errors?.['min']">Age must be at least 18.</div>
<div *ngIf="age?.errors?.['max']">Age cannot exceed 65.</div>
</div>
</div>
<button type="submit" [disabled]="userForm.invalid">Submit</button>
</form>
JavaScript
//app.component.ts
import { NgIf } from '@angular/common';
import { Component, inject } from '@angular/core';
import {
AbstractControl,
FormBuilder,
FormControl,
FormGroup,
FormsModule,
ReactiveFormsModule,
ValidationErrors,
ValidatorFn,
Validators,
} from '@angular/forms';
@Component({
selector: 'app-root',
standalone: true,
imports: [NgIf, ReactiveFormsModule, FormsModule],
templateUrl: './app.component.html',
styleUrl: './app.component.css',
})
export class AppComponent {
userForm: FormGroup;
constructor(private fb: FormBuilder) {
this.userForm = this.fb.group({
name: [
'',
[
Validators.required,
Validators.minLength(3),
Validators.maxLength(20),
],
],
email: ['', [Validators.required, Validators.email]],
password: [
'',
[
Validators.required,
Validators.pattern(
'^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)
(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&]{8,}'
),
],
],
age: ['', [Validators.required, Validators.min(18), Validators.max(65)]],
});
}
get name() {
return this.userForm.get('name');
}
get email() {
return this.userForm.get('email');
}
get password() {
return this.userForm.get('password');
}
get age() {
return this.userForm.get('age');
}
onSubmit() {
if (this.userForm.valid) {
console.log('Form submitted:', this.userForm.value);
}
}
}
Explanation
In this example, we have created a user form with four form controls: name, email, password, and age. Each form control is validated using various validation functions from the Validators class, such as required, minLength, maxLength, email, pattern, min, and max.
The validation errors are displayed in the template using Angular's built-in *ngIf directive, which shows or hides error messages based on the validity of the form controls.
When the user submits the form, the onSubmit method is called, which checks if the form is valid. If the form is valid, the form data can be processed further, such as sending it to a server.
Output

Similar Reads
How to trigger Form Validators in Angular2 ?
In Angular 2, the best way to deal with complex forms is by using Reactive forms. Below we are going to elaborate on how to trigger form validators for login page. In reactive forms, we use FormControl and by using this, we get access to sub-fields of form and their properties. Some of their propert
4 min read
Purpose of the FormsModule in Angular
Forms are widely used in web applications that allow you to provide the data, submit the forms, and interact with the application. In Angular for handling the forms, we use Forms Module which imports several powerful tools for creating, managing, and validating forms. In this article, we'll cover th
5 min read
Explain the purpose of Router services in Angular.
The Router service in Angular is an important component that enables navigation within our single-page application (SPA). It involves mapping URLs to different components or views within the application and rendering the appropriate content based on the requested URL. When a user interacts with navi
6 min read
AngularJS Form Validation
AngularJS performs form validation on the client side. AngularJS monitors the state of the form and input fields (input, text-area, select), and notify the user about the current state. AngularJS also holds information about whether the input fields have been touched, modified, or not. Form input fi
3 min read
How to create class in Angular Project?
In Angular, TypeScript is the primary language for writing code. One of the fundamental concepts in TypeScript is classes, which allow you to define blueprints for creating objects with properties and methods. In this article, we'll explore how to create classes in Angular projects and understand th
2 min read
Purpose of ProvidedIn in Angular
Angular's dependency injection system is a powerful mechanism that helps manage dependencies between components, services, and other parts of the application. One important aspect of this system is the providedIn property, which determines the scope and visibility of a service or module. In this art
4 min read
How to perform custom validation in Angular forms?
Angular's built-in form controls provide a set of predefined validators for common validation such as required fields, email format, and minimum/maximum values. However, there may be cases where you need to implement custom validation logic specific to your application's requirements. Angular offers
4 min read
How to Validate Data in AngularJS ?
In this article, we will know to validate the data in Angular JS, along with understanding the various ways to validate the data through the examples. AngularJS allows client-side form validation. Form validation is necessary because it ensures that the data in the form is correct, complete, and are
10 min read
Purpose of NgModule Decorator in Angular
The NgModule decorator in Angular is like a blueprint for organizing and configuring different parts of your application. It's like a set of instructions that tells Angular how to assemble the various components, directives, pipes, and services into cohesive units called modules. These modules help
5 min read
Purpose of the ngOnInit() method in Angular
ngOnInit is a lifecycle hook in Angular that is called after the constructor is called and after the componentâs inputs have been initialized. It is used to perform any additional initialization that is required for the component. ngOnInit is commonly used to call services or to set up subscriptions
3 min read