← Back to Chapters

Template Forms Validation

✅ Template Forms Validation

? Template-driven Forms ✔️ Validation ? User Input

? Quick Overview

Template-driven forms validation in Angular lets you validate user input directly in the HTML template using built-in HTML validators and Angular directives like ngModel and ngForm. Angular keeps track of the form state (valid, invalid, touched, dirty, submitted) so that you can show or hide validation error messages dynamically and control when the user is allowed to submit the form.

? Key Concepts

  • Template-driven forms use HTML templates with Angular directives such as ngModel and ngForm.
  • Form model is created automatically by Angular based on your template.
  • Built-in validators like required, minlength, and email enforce basic rules.
  • Form control state (e.g., valid, invalid, touched, dirty, pristine, submitted) drives error display.
  • Error messages are usually shown conditionally using *ngIf and control errors (e.g., control.errors?.required).
  • Submit button can be enabled/disabled based on form.valid to prevent invalid submissions.

? Syntax & Theory

  • Attach ngForm to the form using a template reference:
    <form #userForm="ngForm"> ... </form>
  • Bind each input with ngModel and a name:
    <input name="name" [(ngModel)]="user.name" required minlength="3">
  • Access control state with template reference variables:
    #nameRef="ngModel" then use nameRef.valid, nameRef.invalid, etc.
  • Display validation messages conditionally:
    *ngIf="nameRef.errors?.required", *ngIf="nameRef.errors?.minlength".
  • Prevent invalid submit:
    [disabled]="!userForm.form.valid" on the submit button.

? Code Example – Template Forms Validation

? View Code Example
// app.component.ts - template-driven form with validation
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  user = { name: '', email: '' };

  submitForm(form: any) {
    console.log('Form Submitted', this.user);
    console.log('Is form valid?', form.valid);
  }
}

// app.component.html - template with Angular validation
<form #userForm="ngForm" (ngSubmit)="submitForm(userForm)">
  <label for="name">Name:</label>
  <input
    id="name"
    type="text"
    name="name"
    [(ngModel)]="user.name"
    required
    minlength="3"
    #nameRef="ngModel"
  />

  <div *ngIf="nameRef.invalid && (nameRef.dirty || nameRef.touched || userForm.submitted)">
    <span *ngIf="nameRef.errors?.required">Name is required.</span>
    <span *ngIf="nameRef.errors?.minlength">Name must be at least 3 characters.</span>
  </div>

  <br /><br />

  <label for="email">Email:</label>
  <input
    id="email"
    type="email"
    name="email"
    [(ngModel)]="user.email"
    required
    email
    #emailRef="ngModel"
  />

  <div *ngIf="emailRef.invalid && (emailRef.dirty || emailRef.touched || userForm.submitted)">
    <span *ngIf="emailRef.errors?.required">Email is required.</span>
    <span *ngIf="emailRef.errors?.email">Invalid email format.</span>
  </div>

  <br /><br />

  <button type="submit" [disabled]="!userForm.form.valid">Submit</button>
</form>

? Live Output / What Happens?

  • When the page loads, the form is initially invalid because name and email are empty.
  • Angular creates a NgForm instance (userForm) and form controls for name and email.
  • As the user types:
    • nameRef and emailRef update their state (dirty, touched, valid, etc.).
    • Error messages appear only when a control is invalid and has been touched/edited or the form is submitted.
  • The Submit button stays disabled until userForm.form.valid becomes true.
  • When the user clicks Submit with a valid form, submitForm() runs and logs the user object and form validity.

? Typical Use Cases

  • Simple contact forms (name, email, message) in small to medium apps.
  • Signup / login forms where logic is mostly template-side.
  • Quick prototypes where reactive forms are not necessary.
  • Forms with straightforward validation rules using built-in validators.

✅ Tips & Best Practices

  • Always set the name attribute on inputs so that ngModel can register them with the form.
  • Use local references like #nameRef="ngModel" to keep templates clean and readable.
  • Combine HTML5 validators (required, minlength, type="email") with Angular directives.
  • Show error messages only after the field is touched/dirty or after form submission for a better user experience.
  • Group related controls logically to keep your template maintainable.
  • Log form state in the console during development to understand how Angular tracks validity.

? Try It Yourself

  • Create a registration form with username, email, and password fields using template-driven forms.
  • Add validation rules: username (required, minlength), email (required, valid email), password (required, minlength).
  • Show error messages only after the user has interacted with the inputs or after submit is attempted.
  • Add a confirm password field and validate that it matches the original password using a custom check in the component.
  • Disable the submit button until the entire form is valid and log the final form data on submission.