Middle
What are validators in reactive forms? What do they accept and return?
sobes.tech AI
Answer from AI
Validators in Angular reactive forms are functions that check the correctness of a form's value or its field.
-
What they accept: The validator receives the current state of the form control (e.g.,
FormControl) as an object. -
What they return:
- If the value is valid — they return
null. - If there are errors — they return an object with error keys and additional information, for example
{ required: true }.
- If the value is valid — they return
A simple validator example that checks if the value is not empty:
import { AbstractControl, ValidationErrors } from '@angular/forms';
function notEmptyValidator(control: AbstractControl): ValidationErrors | null {
return control.value && control.value.trim() !== '' ? null : { empty: true };
}
Thus, validators allow centralized and declarative validation of form data and error display management.