Angular — Validation
Built-in Validators
import { Validators } from '@angular/forms';
form = new FormGroup({
name: new FormControl('', Validators.required),
email: new FormControl('', [Validators.required, Validators.email]),
age: new FormControl('', [Validators.min(18), Validators.max(120)]),
password: new FormControl('', [Validators.minLength(8)])
});
Template-Driven Validation
<form #form="ngForm">
<input name="email" ngModel required email #email="ngModel">
<div *ngIf="email.invalid && email.touched">
<div *ngIf="email.errors?.['required']">Email is required</div>
<div *ngIf="email.errors?.['email']">Invalid email</div>
</div>
</form>
Reactive Forms Validation
<form [formGroup]="form">
<input formControlName="email">
<div *ngIf="form.get('email')?.invalid && form.get('email')?.touched">
<div *ngIf="form.get('email')?.errors?.['required']">Required</div>
<div *ngIf="form.get('email')?.errors?.['email']">Invalid email</div>
</div>
</form>
Custom Validators
function forbiddenNameValidator(control: FormControl): { [key: string]: any } | null {
const forbidden = /admin/.test(control.value);
return forbidden ? { forbiddenName: true } : null;
}
form = new FormGroup({
username: new FormControl('', forbiddenNameValidator)
});
Form States
| State | Description |
|---|---|
| valid | All rules pass |
| invalid | Has errors |
| pristine | Not touched |
| touched | User interacted |
| dirty | Value changed |
Mini Practice
- Add built-in validators
- Display error messages
- Create custom validators
- Style invalid fields
Up Next
Continue with Methods — component methods.
Related Topics
Frequently Asked Questions about Validation
What is Validation in Angular?
Validation is a fundamental concept in Angular. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Validation?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Validation.
Why is Validation important in Angular?
Validation is essential for Angular development. Understanding this concept will help you write better code and solve real-world problems more effectively.