How to do validations in reactive forms Angular ?
Validations play a crucial role in ensuring data integrity and user experience in reactive forms in Angular. Here are the different ways to implement validation in your forms:
1. Built-in validators:
Angular provides a set of built-in validators available through the Validators class. These include:
required: Ensures the field has a value.
minLength(length): Requires the value to have at least the specified length.
maxLength(length): Limits the value to the specified maximum length.
pattern(regex): Validates the value against a regular expression.
email: Checks if the value is a valid email address.
Example:
TypeScript
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
const myForm = new FormGroup({
name: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
message: ['', Validators.minLength(10)]
});
2. Custom validators:
For more complex validation rules, you can create custom validator functions. These functions take the form control value as input and return an error object if the validation fails.
Example:
TypeScript
myCustomValidator(control: FormControl) {
if (control.value.length < 5) {
return { 'minlength': { requiredLength: 5, actualLength: control.value.length } };
}
return null;
}
const myForm = new FormGroup({
name: ['', Validators.required],
// ... other fields
age: ['', this.myCustomValidator]
});
3. Async validators:
For validations that require asynchronous checks (e.g., checking username availability on a server), you can use async validators. These are functions that return an observable that resolves to an error object or null.
Example:
TypeScript
import { AsyncValidatorFn, FormBuilder, FormGroup } from '@angular/forms';
import { of } from 'rxjs';
import { delay } from 'rxjs/operators';
const usernameAvailableValidator: AsyncValidatorFn = (control) => {
return of(null).pipe(
delay(2000), // Simulate server delay
map(() => {
if (control.value === 'unavailable') {
return { 'usernameTaken': true };
}
return null;
})
);
};
const myForm = new FormGroup({
username: ['', usernameAvailableValidator]
});
Additional tips:
Use the formControlName directive in your template to bind form controls to input elements.
Access validation errors and status using properties like control.touched, control.errors, and control.dirty.
Display validation errors to the user clearly and provide appropriate feedback.
Leverage form groups to perform validation across multiple controls or nested sections of your form.
By effectively combining these validation techniques, you can build robust and user-friendly reactive forms in your Angular applications, ensuring accurate data collection and a smooth user experience.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.