Form validation helps check user input before sending it. Template attributes make it easy to add simple rules right in the HTML.
Form validation with template attributes in Angular
<input type="text" name="fieldName" required minlength="3" maxlength="10" pattern="[a-zA-Z]+" #fieldName="ngModel" ngModel>
Use required to make a field mandatory.
Use minlength, maxlength, and pattern to add more rules.
<input type="email" name="email" required #email="ngModel" ngModel>
<input type="text" name="username" required minlength="4" maxlength="12" #username="ngModel" ngModel>
<input type="password" name="password" required pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}$" #password="ngModel" ngModel>
This Angular component shows a simple form with name and email fields. Both fields use template attributes for validation. Error messages appear when the user touches a field and leaves it invalid. The submit button is disabled until the form is valid. When submitted, an alert shows success.
import { Component } from '@angular/core'; @Component({ selector: 'app-simple-form', template: ` <form #formRef="ngForm" (ngSubmit)="submitForm()"> <label for="name">Name:</label> <input type="text" id="name" name="name" required minlength="3" maxlength="15" #name="ngModel" ngModel> <div *ngIf="name.invalid && name.touched" style="color: red;"> <small *ngIf="name.errors?.required">Name is required.</small> <small *ngIf="name.errors?.minlength">Name must be at least 3 characters.</small> <small *ngIf="name.errors?.maxlength">Name cannot exceed 15 characters.</small> </div> <label for="email">Email:</label> <input type="email" id="email" name="email" required #email="ngModel" ngModel> <div *ngIf="email.invalid && 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]="formRef.invalid">Submit</button> </form> ` }) export class SimpleFormComponent { submitForm() { alert('Form submitted successfully!'); } }
Use #fieldName="ngModel" to access validation state in the template.
Validation messages show only after the user touches the input to avoid confusion.
Disabling the submit button prevents sending invalid data.
Template attributes let you add simple validation rules directly in HTML.
Angular's ngModel and template references help show validation feedback.
Always give users clear messages and disable submit until the form is valid.