Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk3 min

How to Add Validation to an Angular Form

Learn how to validate reactive and template-driven Angular forms, show useful errors, and handle custom, asynchronous, and runtime validation.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To validate an Angular form, choose reactive forms or template-driven forms, add validators to the controls, and show errors after the user has interacted with the form. Reactive forms define the model and validator functions in the component; template-driven forms use directives and validation attributes in the template.

Choose reactive or template-driven forms

Approach Where validation is defined Best fit
Reactive forms In the component’s form model, using validator functions Forms that need an explicit model, direct access to state, or room to scale
Template-driven forms In the template, using directives and validation attributes Small or simple forms where template-based binding is sufficient

Angular describes reactive forms as explicit and model-driven, while template-driven forms rely on directives and two-way binding. See Angular’s forms overview and reactive forms guide. The examples below use APIs documented by Angular; check them against the version installed in your project.

As an Amazon Associate I earn from qualifying purchases.

Add validation to a reactive form

Import Validators from @angular/forms and pass validator functions when you create a control. For example, require a value and set a minimum length:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { FormControl, Validators } from '@angular/forms';

name = new FormControl('', [Validators.required, Validators.minLength(4)]);

Keep the HTML required attribute on the input when appropriate for accessibility. The Angular validator applies form validation; the attribute also communicates that the field is required in the markup.

In the template, display a message when the control is invalid and the user has edited or visited it. Then check the relevant error key:

<input [formControl]="name" required>

<div *ngIf="name.invalid && (name.dirty || name.touched)">
  <p *ngIf="name.hasError('required')">Name is required.</p>
  <p *ngIf="name.hasError('minlength')">Enter at least four characters.</p>
</div>

Angular’s validation guide recommends checking dirty or touched so errors do not appear before the user has had a chance to edit the field. The built-in validator functions and their error keys are documented in the Validators API.

Write a custom synchronous validator

A reactive custom validator receives an AbstractControl. Return null when its value passes the rule, or an object describing the error when it fails:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { AbstractControl, ValidationErrors } from '@angular/forms';

export function noWhitespace(control: AbstractControl): ValidationErrors | null {
  return control.value?.trim() ? null : { whitespace: true };
}

Add the function to a control’s validator list, then check its error key in the template. For rules that depend on multiple fields, attach a cross-field validator to the relevant form group and show the group error after the user has interacted with the form.

Add validation to a template-driven form

For template-driven forms, add supported attributes such as required and minlength to the input. Angular matches those attributes to validator functions. Export ngModel to a template variable to inspect the control’s state and errors:

<input name="name" ngModel required minlength="4" #name="ngModel">

<div *ngIf="name.invalid && (name.dirty || name.touched)">
  <p *ngIf="name.errors?.['required']">Name is required.</p>
  <p *ngIf="name.errors?.['minlength']">Enter at least four characters.</p>
</div>

To add a custom template-driven validator, implement it in a directive and register the directive with NG_VALIDATORS. Angular’s form validation guide covers built-in and custom validation in both approaches.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Validate asynchronously

Use an async validator for checks that need asynchronous work, such as a server-side lookup. It returns a Promise or Observable that resolves to null for valid input or a validation-error object for invalid input. Angular runs async validators only after synchronous validators pass. An Observable used for validation must complete.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

While the check is running, the control can be pending. Use that state to show a brief progress message rather than implying that the value has already passed:

<p *ngIf="username.pending">Checking username…</p>

A remote check on every keystroke can create unnecessary requests. For the relevant control, consider setting updateOn: 'blur' or updateOn: 'submit' so validation runs less frequently.

Change validators at runtime

After adding, removing, replacing, or clearing validators dynamically, call updateValueAndValidity() on the control so Angular recalculates its status. Angular provides corresponding operations for asynchronous validators. See the validation guide for the supported runtime methods.

Angular validation and browser validation

Angular disables native browser form validation by default with novalidate, allowing Angular to manage validation feedback. To enable native browser validation alongside Angular’s checks, add ngNativeValidate to the form. Choose deliberately: browser validation may add its own feedback behavior in addition to messages rendered by your Angular template.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.