Back to course

Built-in Validation in Reactive Forms (Required, MinLength)

The Complete Angular Developer: From Zero to Hero

47. Built-in Validation in Reactive Forms

In Reactive Forms, validators are functions defined within the component class and passed to the FormControl instance when created. Angular provides many standard validation functions in the Validators class.

1. Applying Built-in Validators

Validators are passed as the second argument (or third, if using async validators) to the FormControl constructor, usually as an array.

typescript import { Validators } from '@angular/forms';

// ... inside constructor or ngOnInit

this.loginForm = this.fb.group({ username: ['', [ Validators.required, // Must not be empty Validators.minLength(5), // Must have at least 5 chars Validators.pattern(/[a-zA-Z0-9]+/) ]], password: ['', [Validators.required]] });

2. Displaying Validation Errors in the Template

We use the get() method on the FormGroup to retrieve the control instance and check its status and specific error keys via the errors property.

html

Username is mandatory.

Min length is 5. Current: {{ usernameControl.errors['minlength'].actualLength }}

Key Difference from TDF: In Reactive Forms, validation errors are accessed via control.errors (an object mapping error keys to their values), which we check using hasError(), or the safe navigation operator ?..