Reactive form validations in Angular

 In Angular, reactive forms provide a way to build and manage forms using FormControl, FormGroup, and FormArray. Validations in reactive forms can be handled in a very organized way, allowing you to manage form state, validation, and error handling directly within your component. Let's go through how you can implement validation in a reactive form.

Steps to Implement Reactive Form Validation:

  1. Import ReactiveFormsModule: Ensure that ReactiveFormsModule is imported into your module.

    typescript
    import { ReactiveFormsModule } from '@angular/forms'; @NgModule({ imports: [ReactiveFormsModule], }) export class AppModule {}
  2. Create the Form Model: In your component, define the form structure using FormGroup and FormControl objects.

    typescript
    import { Component } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-reactive-form', templateUrl: './reactive-form.component.html', styleUrls: ['./reactive-form.component.css'] }) export class ReactiveFormComponent { myForm: FormGroup; constructor(private fb: FormBuilder) { this.myForm = this.fb.group({ name: ['', [Validators.required, Validators.minLength(3)]], email: ['', [Validators.required, Validators.email]], age: ['', [Validators.required, Validators.min(18)]], }); } onSubmit() { if (this.myForm.valid) { console.log('Form Value:', this.myForm.value); } else { console.log('Form is invalid'); } } }
  3. HTML Template for the Form: The template binds form controls to the form group and displays validation errors accordingly.

    html
    <form [formGroup]="myForm" (ngSubmit)="onSubmit()"> <label for="name">Name:</label> <input id="name" formControlName="name" type="text" /> <div *ngIf="myForm.get('name').invalid && myForm.get('name').touched"> <div *ngIf="myForm.get('name').hasError('required')">Name is required</div> <div *ngIf="myForm.get('name').hasError('minlength')">Name must be at least 3 characters</div> </div> <label for="email">Email:</label> <input id="email" formControlName="email" type="email" /> <div *ngIf="myForm.get('email').invalid && myForm.get('email').touched"> <div *ngIf="myForm.get('email').hasError('required')">Email is required</div> <div *ngIf="myForm.get('email').hasError('email')">Please enter a valid email</div> </div> <label for="age">Age:</label> <input id="age" formControlName="age" type="number" /> <div *ngIf="myForm.get('age').invalid && myForm.get('age').touched"> <div *ngIf="myForm.get('age').hasError('required')">Age is required</div> <div *ngIf="myForm.get('age').hasError('min')">Age must be at least 18</div> </div> <button type="submit" [disabled]="myForm.invalid">Submit</button> </form>
  4. Common Validators:

    • Validators.required: Ensures the field is not empty.
    • Validators.email: Ensures the field is a valid email format.
    • Validators.minLength(length): Ensures the input has at least the specified number of characters.
    • Validators.min(number): Ensures the value is greater than or equal to a number.
    • Validators.max(number): Ensures the value is less than or equal to a number.
  5. Form Validation Status: You can check the status of the form or individual controls using properties like valid, invalid, touched, dirty, pristine, etc.

    • myForm.valid: Checks if all controls in the form are valid.
    • myForm.invalid: Checks if any control is invalid.
    • myForm.get('name').touched: Returns true if the control has been touched.
    • myForm.get('name').dirty: Returns true if the control's value has been modified.

Advanced Validation Example

If you want to add custom validations, you can define your own validator function.

  1. Custom Validator:

    typescript
    import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms'; // Custom validator for age to check if it's an adult (>= 18) export function adultAgeValidator(): ValidatorFn { return (control: AbstractControl): ValidationErrors | null => { const value = control.value; return value && value < 18 ? { adultAge: true } : null; }; }
  2. Applying Custom Validator:

    typescript
    import { Component } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { adultAgeValidator } from './validators/adult-age.validator'; @Component({ selector: 'app-reactive-form', templateUrl: './reactive-form.component.html', styleUrls: ['./reactive-form.component.css'] }) export class ReactiveFormComponent { myForm: FormGroup; constructor(private fb: FormBuilder) { this.myForm = this.fb.group({ name: ['', [Validators.required, Validators.minLength(3)]], email: ['', [Validators.required, Validators.email]], age: ['', [Validators.required, Validators.min(18), adultAgeValidator()]], }); } onSubmit() { if (this.myForm.valid) { console.log('Form Value:', this.myForm.value); } else { console.log('Form is invalid'); } } }
  3. Custom Validator in Template:

    html
    <div *ngIf="myForm.get('age').hasError('adultAge')">You must be at least 18 years old.</div>

Summary

  • Reactive forms in Angular provide a robust way to handle complex form logic and validations.
  • You can apply both built-in and custom validators to individual controls.
  • The validation status is available directly in the template to provide feedback to the user.
  • For custom validations, you can create custom validator functions and apply them to form controls.

This is a basic introduction to reactive form validations in Angular. You can expand on this to create more complex forms with dynamic validation, async validations, or cross-field validation depending on your needs.

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

Building strong foundational knowledge in frontend development topics