Overview
Mat Dynamic Form leverages Angular’s built-in validation system, supporting both synchronous and asynchronous validators at the field level and globally across the entire form.Types of Validators
Mat Dynamic Form supports all Angular validator types:- Synchronous Validators: Execute immediately and return validation results
- Asynchronous Validators: Return Promises or Observables (e.g., API validation)
Built-in Angular Validators
Angular provides many validators out of the box via theValidators class:
Field-Level Validators
Add validators directly to individual nodes:Single Validator
Multiple Validators
Validator Examples by Node Type
Global Validators
Apply validators to all fields in the form:Global validators are combined with field-level validators. Both sets of validators will be applied to each field.
Validate Disabled Fields
By default, disabled fields are not validated. To validate them:Custom Validators
Create custom validation logic using Angular’sValidatorFn:
Simple Custom Validator
Parameterized Custom Validator
Password Match Validator Example
Asynchronous Validators
Use async validators for server-side validation (e.g., checking username availability):Email Availability Validator
Dynamic Validation
Add or modify validators at runtime:addValidators()
Adds validators without removing existing ones:setValidator()
Replaces all existing validators:addAsyncValidators()
setAsyncValidator()
Conditional Validation Example
Displaying Validation Errors
Error Messages
Use theerrorMessage property for custom error display:
Dynamic Error Messages
Access specific validation errors programmatically:Setting Errors Manually
Validation Best Practices
- Combine Validators: Use both client-side and async validators for comprehensive validation.
- Provide Helpful Hints: Guide users with clear validation requirements.
- Debounce Async Validators: Prevent excessive API calls.
- Handle Validation Errors Gracefully: Provide fallbacks for async validation failures.
- Use Global Validators Sparingly: Only use global validators for rules that truly apply to all fields.
Complete Validation Example
Related Concepts
- Form Structure - Accessing and managing validators
- Nodes - Applying validators to different field types
- Actions - Implementing custom validation logic with events
