Popular Posts

July 22, 2024

How do you perform form validation in Angular

 

In Angular, form validation can be performed using both template-driven forms and reactive forms. Here’s how you can implement validation in each approach:

Template-Driven Forms:

  1. Template Setup:

    • Use Angular directives like ngModel for two-way data binding and ngForm for form management.
    • Add HTML attributes like required, minlength, maxlength, etc., for basic validation.
  2. Validation Directives:

    • Angular provides directives like required, minlength, maxlength, pattern, etc., which can be applied to form controls (input, select, textarea) directly in the template.
  3. Validation Errors:

    • Angular automatically adds CSS classes (ng-valid, ng-invalid) and updates the ngModel object with validation states (valid, invalid, touched, untouched, etc.).
    • Display validation messages based on the ngModel's $error object.
  4. Example:

<form #myForm="ngForm" (ngSubmit)="onSubmit()">
  <input type="text" name="username" [(ngModel)]="user.username" required minlength="3">
  <div *ngIf="myForm.controls['username'].invalid && (myForm.controls['username'].dirty || myForm.controls['username'].touched)">
    <div *ngIf="myForm.controls['username'].errors.required">Username is required.</div>
    <div *ngIf="myForm.controls['username'].errors.minlength">Username must be at least 3 characters long.</div>
  </div>
  <button type="submit" [disabled]="myForm.invalid">Submit</button>
</form>


How do you perform form validation in Angular

Reactive Forms:

  1. Form Control Initialization:

    • Define form controls (FormControl), form groups (FormGroup), and form arrays (FormArray) in the component class using FormBuilder or directly.
  2. Validators:

    • Use built-in validators (Validators.required, Validators.minLength, Validators.maxLength, Validators.pattern, etc.) when creating form controls.
  3. Validation Errors:

    • Access form control validation states using properties like invalid, errors, dirty, touched, etc., directly in the component class.
  4. Example:

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

export class MyComponent {
  myForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
      username: ['', [Validators.required, Validators.minLength(3)]],
      email: ['', [Validators.required, Validators.email]],
      password: ['', Validators.required],
      confirmPassword: ['', Validators.required]
    });
  }

  onSubmit() {
    console.log(this.myForm.value);
  }
}

Summary:

  • Template-Driven Forms: Validation is primarily handled using template directives (ngModel, ngForm, etc.) and HTML attributes (required, minlength, etc.).
  • Reactive Forms: Validation is defined programmatically using FormControl, FormGroup, and FormArray, with built-in and custom validators.

Both approaches provide robust ways to implement form validation in Angular applications. Reactive forms offer more flexibility and control, especially for complex forms and dynamic validations, while template-driven forms are simpler to set up for basic forms with straightforward validation requirements. Choose the approach that best suits your application’s needs and complexity.


No comments:
Write comments