Add Validation Rules to Our Forms
Discover how Angular allows to apply the validation rules to the client forms.
Validating form fields on the client side helps ensure that the data reaching the server is in good shape and provides immediate feedback, improving the user experience for our application. However, this only partially removes work from the server-side. The backend is always considered the last guard, where stricter checks are executed because we can’t trust client data. In fact, not only might the user provide some invalid values—for example, a password with only three characters—but client-side validation can be easily bypassed. Therefore, client-side form validation must always be coupled with its server-side counterpart.
Angular already provides some built-in validators that mirror standard HTML attributes and cover the most common requirements. This lesson will describe the available validators and how we can apply them to our reactive forms.
The Validators
class
The Validators
class contains the available built-in validators. Following is the complete list of available methods with their parameters:
class Validators {static min(min: number): ValidatorFnstatic max(max: number): ValidatorFnstatic required(control: AbstractControl<any, any>): ValidationErrors | nullstatic requiredTrue(control: AbstractControl<any, any>): ValidationErrors | nullstatic email(control: AbstractControl<any, any>): ValidationErrors | nullstatic minLength(minLength: number): ValidatorFnstatic maxLength(maxLength: number): ValidatorFnstatic pattern(pattern: string | RegExp): ValidatorFnstatic nullValidator(control: AbstractControl<any, any>): ValidationErrors | nullstatic compose(validators: ValidatorFn[]): ValidatorFn | nullstatic composeAsync(validators: AsyncValidatorFn[]): AsyncValidatorFn | null}
The method names are self-explanatory, but it’s worth elaborating on some of the less obvious ones.
pattern(pattern:
...