Sub topic 6
Validating with required, minlength, pattern, and email
This chapter assumes you can write a standalone Angular component, you know basic template syntax (property binding, event binding, template reference variables), and you have already bound an input with [(ngModel)] inside a form. Here you add validation using plain HTML attributes.
How validation attributes work
Once FormsModule is imported, Angular attaches validator directives to any ngModel control that carries a matching attribute. You write required, and Angular runs its own required check. The control's errors object, valid flag, and CSS classes then update on every change.
| Attribute | Passes when | Error key |
|---|---|---|
| `required` | The value is not empty | `required` |
| `minlength="3"` | The value has at least 3 characters | `minlength` |
| `maxlength="20"` | The value has at most 20 characters | `maxlength` |
| `pattern="..."` | The value matches the regular expression | `pattern` |
| `email` | The value looks like an email address | `email` |
A worked example
This component validates a name, an email, and a username that must start with a letter.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-account',
imports: [FormsModule],
template: `
<form #f="ngForm" (ngSubmit)="onSubmit()">
<label for="name">Name</label>
<input id="name" name="name" [(ngModel)]="model.name"
#name="ngModel" required minlength="3" />
@if (name.invalid && (name.dirty || name.touched)) {
<p role="alert">
@if (name.errors?.['required']) { Name is required. }
@if (name.errors?.['minlength']) {
Use at least {{ name.errors?.['minlength'].requiredLength }} characters.
}
</p>
}
<label for="email">Email</label>
<input id="email" name="email" type="email" [(ngModel)]="model.email"
#email="ngModel" required email />
@if (email.invalid && (email.dirty || email.touched)) {
<p role="alert">Enter a valid email address.</p>
}
<label for="username">Username</label>
<input id="username" name="username" [(ngModel)]="model.username"
#username="ngModel" required pattern="[A-Za-z][A-Za-z0-9_]*" />
@if (username.invalid && (username.dirty || username.touched)) {
<p role="alert">Start with a letter. Use letters, digits, or underscores.</p>
}
<button type="submit" [disabled]="f.invalid">Create account</button>
</form>
`,
})
export class AccountComponent {
model = { name: '', email: '', username: '' };
onSubmit() {
console.log('Submitted', this.model);
}
}Each input exports its NgModel into a template variable (#name="ngModel"). That variable gives you errors, invalid, dirty, and touched. The submit button reads f.invalid from the form, which is invalid while any child control is invalid.
Details that cause bugs
- Empty values pass most validators.
minlength,pattern, andemailskip empty input. Onlyrequiredrejects an empty value. Pair each of them withrequiredwhen the field is mandatory. - Patterns are anchored. With the
patternattribute, Angular wraps your string in^...$. Write[A-Za-z]+, not^[A-Za-z]+$. The error object includesrequiredPatternandactualValue. minlengthblocks only by validity. It does not stop the user from typing. The control just becomes invalid.emailis a loose check. It accepts what looks like an address, not one that exists. Confirm real ownership on the server.nameis mandatory inside a form. AnngModelcontrol inside a<form>needs anameattribute, or Angular throws an error at runtime.
Reading errors
The errors property is null when the control is valid. When it is invalid, it is an object keyed by validator name. Use optional chaining with bracket access, name.errors?.['minlength'], because strict templates reject dotted access on an index signature.
Exercise
A field has required pattern="[0-9]{5}". The user types "123456". Is the control valid, and which error key is set?
Show answer
It is invalid. Angular anchors the pattern, so six digits do not match exactly five digits. The errors object contains a pattern key, with requiredPattern and actualValue inside it.
Exercise
A user leaves an optional field with minlength="5" empty. Does the control report a minlength error?
Show answer
No. minlength ignores empty values, so the control is valid. Add required if the field must be filled in.