Skip to main content
Form validation is essential for ensuring data quality and providing a good user experience. Angular provides built-in validators and allows you to create custom validators for both reactive and template-driven forms.

Built-in Validators

Angular includes several built-in validators in the Validators class:

required

Requires a non-empty value

email

Validates email format

min

Minimum numeric value

max

Maximum numeric value

minLength

Minimum string/array length

maxLength

Maximum string/array length

pattern

Validates against regex

requiredTrue

Requires true value (checkboxes)

nullValidator

No-op validator

Using Validators in Reactive Forms

Single Validator

packages/forms/src/validators.ts

Multiple Validators

packages/forms/src/validators.ts

Displaying Validation Errors

Using Validators in Template-Driven Forms

Built-in Validation Directives

Custom Validators

Creating a Custom Validator Function

packages/forms/src/validators.ts

Cross-Field Validation

Validate multiple fields together:
packages/forms/src/validators.ts

Custom Validator Directive

For template-driven forms:
packages/forms/src/directives/validators.ts

Async Validators

Async validators return a Promise or Observable for server-side validation:
packages/forms/src/validators.ts

Validation Status

Form controls have several status properties:

Dynamic Validation

Add or remove validators dynamically:

Validation Error Messages

Create reusable error message components:

Best Practices

Check touched or dirty before showing errors to avoid overwhelming users.
Tell users exactly what they need to fix, including requirements.
Debounce async validators to reduce server calls.
Use Validators.compose() to combine multiple validators.
Remember to call updateValueAndValidity() after changing validators.

Testing Form Validation

Next Steps

Reactive Forms

Learn more about reactive forms

Template-Driven Forms

Learn more about template-driven forms