Angular Form Validation
Learn how Angular validates user input using built-in validators, control states and validation messages in reactive and template-driven forms.
What is Form Validation?
Form validation checks whether the data entered by a user satisfies the rules required by the application.
For example, a course enquiry form may require a name, valid email address, mobile number and selected course.
Angular provides built-in validators and form states that make it easier to identify invalid input and show useful validation messages.
Form Validation Flow
Main Validation Concepts
Required
Ensures that a required field is not empty.
Checks whether an email value satisfies the validator.
Min / Max Length
Controls the allowed length of a field value.
Form State
Tracks valid, invalid, touched, dirty and related states.
Angular Validators
Angular provides built-in validators through the Validators class for reactive forms.
These validators can be combined to create validation rules for individual form controls.
import { FormControl, Validators }
from '@angular/forms';
Validators.required
Validators.required checks that a control contains a value.
It is commonly used for fields such as name, course and mobile number.
name = new FormControl(
'',
Validators.required
);
Validators.email
Validators.email applies Angular's email validation rule to a form control.
It can be combined with Validators.required when an email field must be provided and valid.
email = new FormControl(
'',
[
Validators.required,
Validators.email
]
);
Validators.minLength
Validators.minLength checks that a control value has at least the specified number of characters.
mobile = new FormControl(
'',
Validators.minLength(10)
);
Validators.maxLength
Validators.maxLength limits the maximum number of characters allowed in a control value.
mobile = new FormControl(
'',
Validators.maxLength(10)
);
Using Multiple Validators
Multiple validators can be applied to the same form control by placing them inside an array.
This allows one field to satisfy more than one validation rule.
email = new FormControl(
'',
[
Validators.required,
Validators.email,
Validators.minLength(5)
]
);
Form Control States
Valid
The control satisfies its validation rules.
Invalid
One or more validation rules are not satisfied.
Touched
The user has interacted with the control.
Dirty
The user has changed the control value.
Validation Errors
Angular provides error information through the control's errors property.
This can be used to determine which validation rule has failed.
const emailControl =
this.registrationForm.get('email');
console.log(
emailControl?.errors
);
Checking Required Error
<div
*ngIf="
registrationForm.get('name')?.hasError('required')
&&
registrationForm.get('name')?.touched
">
Name is required.
</div>
Checking Email Error
<div
*ngIf="
registrationForm.get('email')?.hasError('email')
&&
registrationForm.get('email')?.touched
">
Please enter a valid email address.
</div>
Checking Min Length Error
<div
*ngIf="
registrationForm.get('mobile')?.hasError('minlength')
&&
registrationForm.get('mobile')?.touched
">
Mobile number is too short.
</div>
CIIT Training Institute Validation Example
Suppose CIIT Training Institute has a course enquiry form with fields for name, email and mobile number.
Each field can have its own validation rules before the enquiry is submitted.
import { Component } from '@angular/core';
import {
FormBuilder,
Validators
} from '@angular/forms';
@Component({
selector: 'app-enquiry',
templateUrl: './enquiry.component.html'
})
export class EnquiryComponent {
enquiryForm = this.fb.group({
name: [
'',
Validators.required
],
email: [
'',
[
Validators.required,
Validators.email
]
],
mobile: [
'',
[
Validators.required,
Validators.minLength(10),
Validators.maxLength(10)
]
],
course: [
'',
Validators.required
]
});
constructor(
private fb: FormBuilder
) {
}
}
<form [formGroup]="enquiryForm">
<label>
Name
</label>
<input
type="text"
formControlName="name">
<div
*ngIf="
enquiryForm.get('name')?.invalid
&&
enquiryForm.get('name')?.touched
">
Name is required.
</div>
<label>
Email
</label>
<input
type="email"
formControlName="email">
<div
*ngIf="
enquiryForm.get('email')?.hasError('required')
&&
enquiryForm.get('email')?.touched
">
Email is required.
</div>
<div
*ngIf="
enquiryForm.get('email')?.hasError('email')
&&
enquiryForm.get('email')?.touched
">
Enter a valid email address.
</div>
<label>
Mobile
</label>
<input
type="text"
formControlName="mobile">
<div
*ngIf="
enquiryForm.get('mobile')?.invalid
&&
enquiryForm.get('mobile')?.touched
">
Enter a valid mobile number.
</div>
<button
type="submit"
[disabled]="enquiryForm.invalid">
Submit Enquiry
</button>
</form>
Validation Result
Name: Required
Email: Valid Email Required
Mobile: 10 Characters Required
Submit button: Disabled until form is valid
Validation in Template-driven Forms
Template-driven forms can use HTML validation attributes such as required, email, minlength and maxlength.
The control state can then be inspected through a template reference variable.
<input
type="email"
name="email"
ngModel
required
email
#emailControl="ngModel">
<div
*ngIf="
emailControl.invalid
&&
emailControl.touched
">
Please enter a valid email.
</div>
Checking Complete Form Validation
if (this.enquiryForm.valid) {
console.log(
'Form is valid'
);
}
else {
console.log(
'Form is invalid'
);
}
Form Status
Angular evaluates the validation rules of the registered controls and exposes the overall form status through valid or invalid.
Marking Controls as Touched
When a user submits an incomplete form, it can be useful to mark controls as touched so that their validation messages become visible.
submitForm() {
if (this.enquiryForm.invalid) {
this.enquiryForm.markAllAsTouched();
return;
}
console.log(
this.enquiryForm.value
);
}
Common Validation Rules
| Validator | Purpose | Example |
|---|---|---|
required
|
Ensures a value is provided. |
Validators.required
|
email
|
Applies email validation. |
Validators.email
|
minLength
|
Requires a minimum number of characters. |
Validators.minLength(10)
|
maxLength
|
Limits the maximum number of characters. |
Validators.maxLength(10)
|
invalid
|
Indicates that one or more rules are failing. |
form.invalid
|
Important Points
Required information should be validated before the application processes the form.
Select validators based on the actual requirements of each form field.
Validation messages should clearly explain what the user needs to correct.
Do not process form data until the form satisfies the required validation rules.
Form Validation Best Practices
- Use appropriate validators for each field.
- Display validation messages only when useful to the user.
- Validate required fields before processing submitted data.
- Use meaningful validation messages rather than generic errors.
- Keep validation logic organized and easy to maintain.
- Perform corresponding validation on the backend as well; client-side validation should not be treated as the only security or data-integrity check.
Summary
Angular Form Validation helps ensure that user-entered information satisfies the application's requirements.
Common reactive-form validators include Validators.required, Validators.email, Validators.minLength and Validators.maxLength.
Angular also tracks states such as valid, invalid, touched and dirty. In the next topic, we will learn about Form Submission.