...

/

Add Validation Rules to Our Forms

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 Validatorsclass

The Validators class contains the available built-in validators. Following is the complete list of available methods with their parameters:

Press + to interact
class Validators {
static min(min: number): ValidatorFn
static max(max: number): ValidatorFn
static required(control: AbstractControl<any, any>): ValidationErrors | null
static requiredTrue(control: AbstractControl<any, any>): ValidationErrors | null
static email(control: AbstractControl<any, any>): ValidationErrors | null
static minLength(minLength: number): ValidatorFn
static maxLength(maxLength: number): ValidatorFn
static pattern(pattern: string | RegExp): ValidatorFn
static nullValidator(control: AbstractControl<any, any>): ValidationErrors | null
static compose(validators: ValidatorFn[]): ValidatorFn | null
static 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: ...