0
0
Angularframework~5 mins

Validators (required, minLength, pattern) in Angular

Choose your learning style9 modes available
Introduction

Validators help check if the user typed the right kind of information in a form. They make sure the form is filled out correctly before sending it.

When you want to make sure a user does not leave a form field empty.
When you want to require a minimum number of characters in a text input.
When you want to check if the input matches a specific pattern, like an email or phone number.
When you want to give users instant feedback about mistakes in their form entries.
When you want to prevent submitting a form with invalid or incomplete data.
Syntax
Angular
import { Validators } from '@angular/forms';

this.myForm = new FormGroup({
  name: new FormControl('', [Validators.required, Validators.minLength(3), Validators.pattern('^[a-zA-Z]+$')])
});

Validators.required checks if the field is not empty.

Validators.minLength(n) checks if the input has at least n characters.

Validators.pattern(regex) checks if the input matches the given regular expression.

Examples
This control must have a value; it cannot be empty.
Angular
new FormControl('', Validators.required)
This control requires at least 5 characters typed in.
Angular
new FormControl('', Validators.minLength(5))
This control only accepts numbers (digits) as input.
Angular
new FormControl('', Validators.pattern('^[0-9]+$'))
This control must not be empty, must have at least 4 lowercase letters, and no other characters.
Angular
new FormControl('', [Validators.required, Validators.minLength(4), Validators.pattern('^[a-z]+$')])
Sample Program

This Angular component creates a simple form with one input for username. It uses three validators: required, minLength(3), and pattern to allow only letters. It shows error messages below the input if the user input is invalid. The submit button is disabled until the form is valid.

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

@Component({
  selector: 'app-simple-form',
  template: `
    <form [formGroup]="userForm" (ngSubmit)="submit()">
      <label for="username">Username:</label>
      <input id="username" formControlName="username" aria-describedby="usernameHelp" />
      <div id="usernameHelp" *ngIf="username.invalid && (username.dirty || username.touched)" style="color: red;">
        <div *ngIf="username.errors?.required">Username is required.</div>
        <div *ngIf="username.errors?.minlength">Username must be at least 3 characters.</div>
        <div *ngIf="username.errors?.pattern">Username must contain only letters.</div>
      </div>
      <button type="submit" [disabled]="userForm.invalid">Submit</button>
    </form>
  `
})
export class SimpleFormComponent {
  userForm = new FormGroup({
    username: new FormControl('', [
      Validators.required,
      Validators.minLength(3),
      Validators.pattern('^[a-zA-Z]+$')
    ])
  });

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

  submit() {
    if (this.userForm.valid) {
      alert('Form submitted with username: ' + this.username.value);
    }
  }
}
OutputSuccess
Important Notes

Use Validators.compose to combine multiple validators if needed, but passing an array works well.

Angular runs validators automatically when the user types or changes the input.

Always provide user-friendly error messages to help fix mistakes.

Summary

Validators check user input to keep forms correct and complete.

Use required, minLength, and pattern to cover common validation needs.

Show clear error messages and disable submit until the form is valid.