Form Validation
Validation ensures that users enter correct data. Angular provides built-in validators and also lets you create custom validators. Both template-driven and reactive forms support validation.
Built-in Validators
Common validators include:
required– Field must have a value.minlength– Minimum length.maxlength– Maximum length.pattern– Must match a regular expression.email– Valid email format.min– Minimum numeric value.max– Maximum numeric value.
Displaying Validation Errors
In the template, you can check the control's state using properties like
invalid, touched, dirty, and access specific errors via the errors object.Example for reactive forms:
<div *ngIf="loginForm.get('email').invalid && loginForm.get('email').touched">
<small *ngIf="loginForm.get('email').errors?.required">Email is required.</small>
<small *ngIf="loginForm.get('email').errors?.email">Invalid email format.</small>
</div>
Custom Validators
Sometimes built-in validators aren't enough. You can create your own validator function.
Example: A validator that checks if a username is available (async):
Custom synchronous validator:
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const forbidden = nameRe.test(control.value);
return forbidden ? { forbiddenName: { value: control.value } } : null;
};
}
Use it in reactive forms:
this.profileForm = this.fb.group({
name: ['', [Validators.required, forbiddenNameValidator(/admin/i)]]
});
Custom async validator (for server-side checks):
import { AbstractControl, AsyncValidatorFn, ValidationErrors } from '@angular/forms';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
export function uniqueUsernameValidator(userService: UserService): AsyncValidatorFn {
return (control: AbstractControl): Observable => {
return userService.checkUsername(control.value).pipe(
map(isTaken => isTaken ? { usernameTaken: true } : null)
);
};
}
Two Minute Drill
- Built-in validators: required, minlength, maxlength, pattern, email, min, max.
- Display errors using *ngIf and the errors object.
- Custom validators are functions that return ValidationErrors or null.
- Async validators return Observable or Promise.
- Validators can be combined and reused.
Need more clarification?
Drop us an email at career@quipoinfotech.com
