Q1. What are the built-in validators in Angular?
Angular provides several built-in validators: required, min, max, minlength, maxlength, email, pattern, nullValidator, and compose. They are in the Validators class. For reactive forms, use Validators.required, etc. For template-driven, use HTML5 validation attributes.
Q2. How do you create a custom validator?
A custom validator is a function that returns either null (valid) or a ValidationErrors object. Example:
function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const forbidden = nameRe.test(control.value);
return forbidden ? { forbiddenName: { value: control.value } } : null;
};
}
Q3. How do you show validation error messages?
Check the control''s errors object. Example:
Email is required
Invalid email format
email is a template reference variable with ngModel.Q4. What is cross-field validation?
Cross-field validation validates multiple fields together, like password and confirm password. In reactive forms, you add a validator at the FormGroup level. Example:
form = new FormGroup({...}, { validators: passwordMatchValidator });
Q5. How do you handle async validation?
Use AsyncValidatorFn that returns Promise or Observable. Example for checking username availability:
username: new FormControl('''', [], [this.usernameValidator])
Async validators are called after sync validators pass.