0
0
AngularHow-ToBeginner · 4 min read

How to Use minlength Validator in Angular Forms

In Angular, use the Validators.minLength function to enforce a minimum length on form controls. Apply it in reactive forms by adding it to the control's validator array, or in template-driven forms by using the minlength attribute on input elements.
📐

Syntax

The Validators.minLength function takes a single number argument that specifies the minimum number of characters required. It returns a validator function that Angular uses to check the form control's value length.

In reactive forms, add it like Validators.minLength(5) inside the array of validators for a form control. In template-driven forms, use the minlength attribute on the input element.

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

// Reactive form control with minlength validator
const control = new FormControl('', [Validators.minLength(5)]);

// Template-driven form input
// <input type="text" name="username" minlength="5" ngModel>
💻

Example

This example shows a reactive form with a single input that requires at least 5 characters. The form displays an error message if the input is too short.

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

@Component({
  selector: 'app-minlength-example',
  template: `
    <form [formGroup]="form">
      <label for="name">Name (min 5 chars):</label>
      <input id="name" formControlName="name" />
      <div *ngIf="name.invalid && (name.dirty || name.touched)" style="color: red;">
        <div *ngIf="name.errors?.minlength">
          Minimum length is {{ name.errors.minlength.requiredLength }} characters.
        </div>
      </div>
      <button [disabled]="form.invalid">Submit</button>
    </form>
  `
})
export class MinlengthExampleComponent {
  form = new FormGroup({
    name: new FormControl('', [Validators.minLength(5)])
  });

  get name() {
    return this.form.get('name')!;
  }
}
Output
A form with a text input labeled 'Name (min 5 chars):'. If fewer than 5 characters are typed and the input is touched or changed, a red error message appears: 'Minimum length is 5 characters.'. The submit button is disabled until the input is valid.
⚠️

Common Pitfalls

  • For reactive forms, forgetting to include Validators.minLength inside an array if you have multiple validators.
  • In template-driven forms, using minlength attribute without importing FormsModule can cause it not to work.
  • Not checking touched or dirty before showing errors can confuse users by showing errors immediately.
  • Using minlength on non-text inputs like number inputs will not work as expected.
typescript
/* Wrong: missing array for multiple validators */
new FormControl('', Validators.minLength(5), Validators.required); // Incorrect

/* Right: validators inside an array */
new FormControl('', [Validators.minLength(5), Validators.required]); // Correct
📊

Quick Reference

Use this quick guide to remember how to apply minlength validator in Angular forms:

UsageCode ExampleNotes
Reactive Formsnew FormControl('', [Validators.minLength(5)])Add inside validators array
Template-driven FormsUse minlength attribute on input
Check Errorscontrol.errors?.minlengthAccess minlength error object
Error PropertiesrequiredLength, actualLengthUse to show detailed messages

Key Takeaways

Use Validators.minLength(number) in reactive forms inside the validators array.
In template-driven forms, add minlength attribute to input elements.
Check control.errors?.minlength to detect minlength validation errors.
Show errors only after user interaction using touched or dirty flags.
Always import FormsModule or ReactiveFormsModule as needed.