Reactive Form Validation In Angular

Here are the steps to implement Reactive Form validation in Angular,

Import the ReactiveFormsModule in the module where you want to use Reactive Forms.

import { ReactiveFormsModule } from '@angular/forms';

Define a form in your component by creating an instance of FormGroup class. You can define the form controls and their validation rules using FormControl and Validators classes.

import { FormGroup, FormControl, Validators } from '@angular/forms';

export class MyComponent {
    myForm: FormGroup;
    constructor() {
        this.myForm = new FormGroup({
            username: new FormControl('', [Validators.required, Validators.minLength(3)]),
            email: new FormControl('', [Validators.required, Validators.email]),
            password: new FormControl('', [Validators.required, Validators.minLength(6)])
        });
    }
}

In the HTML template, bind the form controls to the input fields using formControlName directive.

<form [formGroup]="myForm">
  <label for="username">Username</label>
  <input type="text" id="username" formControlName="username">
  <label for="email">Email</label>
  <input type="email" id="email" formControlName="email">
  <label for="password">Password</label>
  <input type="password" id="password" formControlName="password">
  <button type="submit" [disabled]="myForm.invalid">Submit</button>
</form>

You can display error messages based on the validation status of the form controls using the hasError() method.

<div *ngIf="myForm.get('username').dirty && myForm.get('username').hasError('required')"> Username is required. </div>
<div *ngIf="myForm.get('username').dirty && myForm.get('username').hasError('minlength')"> Username must be at least 3 characters long. </div>
<div *ngIf="myForm.get('email').dirty && myForm.get('email').hasError('required')"> Email is required. </div>
<div *ngIf="myForm.get('email').dirty && myForm.get('email').hasError('email')"> Invalid email format. </div>
<div *ngIf="myForm.get('password').dirty && myForm.get('password').hasError('required')"> Password is required. </div>
<div *ngIf="myForm.get('password').dirty && myForm.get('password').hasError('minlength')"> Password must be at least 6 characters long. </div>

You can also display the overall form validation status using the invalid property of the form.

<button type="submit" [disabled]="myForm.invalid">Submit</button>

That's it! Now you have a fully functional Reactive Form with validation in Angular. 

Thanks!! 


Similar Articles