0
0
AngularHow-ToBeginner · 4 min read

How to Validate Form in Angular: Simple Guide with Examples

In Angular, you validate forms by using ReactiveFormsModule or FormsModule with built-in validators like Validators.required. You create a form model, attach validators, and check the form's validity state to show errors or enable submission.
📐

Syntax

Angular provides two main ways to validate forms: reactive forms and template-driven forms. Reactive forms use FormGroup and FormControl classes to define form controls and validators in the component code. Template-driven forms use directives like ngModel and validators in the template.

Validators are functions like Validators.required or Validators.email that check input values. You attach them when creating form controls.

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

// Create a form group with controls and validators
const form = new FormGroup({
  name: new FormControl('', [Validators.required]),
  email: new FormControl('', [Validators.required, Validators.email])
});

// Check if form is valid
if (form.valid) {
  // proceed
} else {
  // show errors
}
💻

Example

This example shows a simple reactive form with two fields: name and email. It validates that both fields are filled and email is in correct format. The form disables the submit button if invalid and shows error messages.

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

@Component({
  selector: 'app-simple-form',
  template: `
    <form [formGroup]="userForm" (ngSubmit)="onSubmit()">
      <label for="name">Name:</label>
      <input id="name" formControlName="name" />
      <div *ngIf="name.invalid && (name.dirty || name.touched)" style="color:red">
        <small *ngIf="name.errors?.required">Name is required.</small>
      </div>

      <label for="email">Email:</label>
      <input id="email" formControlName="email" />
      <div *ngIf="email.invalid && (email.dirty || email.touched)" style="color:red">
        <small *ngIf="email.errors?.required">Email is required.</small>
        <small *ngIf="email.errors?.email">Enter a valid email.</small>
      </div>

      <button type="submit" [disabled]="userForm.invalid">Submit</button>
    </form>
  `
})
export class SimpleFormComponent {
  userForm = new FormGroup({
    name: new FormControl('', [Validators.required]),
    email: new FormControl('', [Validators.required, Validators.email])
  });

  get name() { return this.userForm.get('name')!; }
  get email() { return this.userForm.get('email')!; }

  onSubmit() {
    if (this.userForm.valid) {
      alert('Form Submitted! Name: ' + this.name.value + ', Email: ' + this.email.value);
    }
  }
}
Output
A form with two input fields (Name and Email). Submit button is disabled until both fields are valid. Error messages appear below inputs if invalid. On submit, an alert shows the entered values.
⚠️

Common Pitfalls

  • Not importing ReactiveFormsModule or FormsModule in your Angular module causes errors.
  • Forgetting to check formControl.invalid and formControl.touched before showing errors can confuse users.
  • Using validators incorrectly, like passing a single validator without wrapping in an array when multiple validators are needed.
  • Not disabling the submit button or preventing submission when the form is invalid.
typescript
/* Wrong: Missing ReactiveFormsModule import in app.module.ts */
// This causes form directives to not work

/* Wrong: Showing error without checking touched or dirty */
<div *ngIf="name.invalid">Name is required</div>

/* Right: Check touched or dirty before showing error */
<div *ngIf="name.invalid && (name.touched || name.dirty)">Name is required</div>
📊

Quick Reference

Here is a quick summary of key points for Angular form validation:

ConceptDescription
FormGroupGroups form controls into a single object to track value and validity.
FormControlRepresents a single input field with value and validation state.
Validators.requiredEnsures the field is not empty.
Validators.emailChecks if the input is a valid email format.
formControl.invalidTrue if the control has failed validation.
formControl.touchedTrue if the user has focused and left the control.
[formGroup]Directive to bind the form group in template.
formControlNameDirective to bind individual controls in template.

Key Takeaways

Use ReactiveFormsModule or FormsModule to enable form validation in Angular.
Attach validators like Validators.required and Validators.email to form controls.
Check form and control validity before allowing submission or showing errors.
Show error messages only after the user interacts with the input (touched or dirty).
Always disable submit buttons or prevent submission when the form is invalid.