Sub topic 6
Validating with required, minlength, pattern, and email
This chapter assumes you can write an Angular standalone component and use property and event bindings. It also assumes you have bound an input with [(ngModel)] and know what #f="ngForm" gives you. Here you add validation rules to those inputs and read the results. Control state (touched, dirty) was covered in the previous chapter. Displaying messages gets its own chapter, so this one only shows the minimum needed to see an error.
How validation attributes become validators
In a template-driven form you write HTML attributes, and Angular turns them into validators. When FormsModule is imported, directives match attributes such as required on any element that also has ngModel. Each directive registers a validation function with the control that ngModel creates.
The directives only match when ngModel is present on the same element. A plain <input required> outside a form model is left to the browser.
Angular also adds the novalidate attribute to your <form> elements automatically. This turns off the browser's own validation bubbles, so Angular's rules are the only ones that apply.
Each validator returns null when the value is valid. When the value is invalid, it returns an object of errors. The control merges the results of all its validators into control.errors. If that merged object is null, the control is valid.
The four built-in rules
| Attribute | Passes when | Error key | Error value |
|---|---|---|---|
| `required` | The value is not empty | `required` | `true` |
| `minlength="n"` | The value has at least `n` characters | `minlength` | `{ requiredLength, actualLength }` |
| `pattern="..."` | The value matches the regular expression | `pattern` | `{ requiredPattern, actualValue }` |
| `email` | The value looks like an email address | `email` | `true` |
maxlength also exists and returns a maxlength error with the same shape as minlength. It is not covered further here because it works the same way.
required
required fails for null, undefined, an empty string, and an empty array. The string " " (only spaces) has length 3, so it passes. If whitespace-only input should be rejected, combine required with a pattern or write a custom validator.
On a checkbox, required behaves differently. Angular applies a checkbox-specific validator that fails unless the box is checked. This is the usual way to require "I accept the terms".
You can turn the rule on and off with a binding:
<input name="company" [(ngModel)]="model.company" [required]="model.isBusiness" />When model.isBusiness is false, the validator no longer reports an error. Angular re-runs validation when the bound value changes.
minlength
minlength counts characters in the string. It reports an error only when the value is non-empty and too short. An empty value passes minlength. This is intentional, because emptiness is the job of required. If you want "required and at least 3 characters", use both attributes.
Write it as a plain attribute, minlength="3", or bind a number, [minlength]="minName".
pattern
pattern takes a regular expression. Written as a plain string, Angular anchors it for you by adding ^ at the start and $ at the end, so the whole value must match. This matches the behavior of the HTML pattern attribute.
<input name="zip" [(ngModel)]="model.zip" pattern="[0-9]{5}" />Here 12345 passes, but 123456 fails because the pattern is anchored. If you bind a RegExp object, [pattern]="zipRegex", Angular uses it as written and does not add anchors. Anchor it yourself if you need whole-value matching.
Like minlength, pattern skips empty values. Pair it with required when the field is mandatory.
A common mistake is putting a backslash in a plain attribute, as in pattern="\d{5}". In an HTML attribute the backslash passes through to the regular expression as written, so it usually works. Inside a TypeScript template string, however, the backslash is consumed by the string literal. Write \\d in inline templates, or use [0-9], which avoids the problem.
Add the bare email attribute to an input that has ngModel. Angular's email check is lenient. It accepts a@b because the address has no required top-level domain. Use pattern too, or a custom validator, if you need stricter rules. Empty values pass email, so add required when the field is mandatory.
Note that type="email" alone does not add Angular's validator. It only changes the keyboard and the browser's own checks, which novalidate has disabled.
A complete example
This component combines all four rules and exposes each control's errors through a template reference variable.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-account',
imports: [FormsModule],
template: `
<form #f="ngForm" (ngSubmit)="onSubmit()">
<label for="username">Username</label>
<input
id="username"
name="username"
[(ngModel)]="model.username"
#username="ngModel"
required
minlength="4"
pattern="[a-z0-9_]+"
/>
<p>Username errors: {{ username.errors | json }}</p>
<label for="email">Email</label>
<input
id="email"
name="email"
type="email"
[(ngModel)]="model.email"
#email="ngModel"
required
email
/>
<p>Email errors: {{ email.errors | json }}</p>
<button type="submit" [disabled]="f.invalid">Create account</button>
<p>Form valid: {{ f.valid }}</p>
</form>
`,
})
export class AccountComponent {
model = { username: '', email: '' };
onSubmit() {
console.log('Submitted', this.model);
}
}The json pipe is available in standalone components only if you import JsonPipe. Add JsonPipe to the imports array and import it from @angular/common, or the template will not compile. The corrected declaration is:
imports: [FormsModule, JsonPipe],Try typing into the username field and watch the output:
| Input | `username.errors` |
|---|---|
| (empty) | `{ "required": true }` |
| `ab` | `{ "minlength": { "requiredLength": 4, "actualLength": 2 } }` |
| `Abcd` | `{ "pattern": { "requiredPattern": "^[a-z0-9_]+$", "actualValue": "Abcd" } }` |
| `abcd` | `null` |
Notice the requiredPattern value: it shows the ^ and $ that Angular added. Notice also that an empty value reports only required, not minlength or pattern.
Reading the errors object
A control can fail several rules at once. For example, Ab fails both minlength (too short) and pattern (uppercase letter), so errors contains both keys. Check each key separately instead of assuming only one is present.
In the template, use bracket notation, as in username.errors?.['minlength']. This works under strict templates because errors is typed as an index signature. Dot access fails type checking under noPropertyAccessFromIndexSignature.
The error values carry data you can use in messages. username.errors?.['minlength'].requiredLength gives you the number from the attribute, so you do not need to repeat 4 in your message text.
You can also ask a control about one rule directly:
@if (username.hasError('minlength')) {
<p>Too short.</p>
}hasError returns true when that key exists in errors.
Validity propagates upward
The form is valid only when every control inside it is valid. f.invalid is true while any control fails a rule. That is why [disabled]="f.invalid" on the submit button works as a simple gate.
One caution: a control without a name attribute inside a <form> is a runtime error, because ngModel needs the name to register the control with the form. A missing name is the most common reason validation seems to have no effect on a form.
Common errors
- Validators never fire. The element has no
ngModel, orFormsModuleis not in the component'simports. NG01352: If ngModel is used within a form tag, either the name attribute must be set...Addname="..."to the input.- Short values pass
minlength. The value is empty.minlengthandpatternignore empty strings, so addrequired. - Partial matches pass
pattern. You bound aRegExpwithout^and$. A string attribute is anchored automatically, but a bound regular expression is not. emailacceptsa@b. The built-in check is lenient. Add a stricterpattern.- The error appears before the user types. Validators run immediately on an empty form, so
errorsis already set at load. Gate display with the touched or dirty state, which the next chapter covers.
Exercise
A field has name="code", [(ngModel)]="model.code", and pattern="[A-Z]{3}", with no required. What does errors contain for the values (a) an empty string, (b) ABCD, (c) ABC? Then change the field so that a blank value is also rejected, and say which attribute you add.
Show answer
(a) null, because pattern skips empty values. (b) { pattern: { requiredPattern: '^[A-Z]{3}$', actualValue: 'ABCD' } }, because the string pattern is anchored and ABCD is four characters. (c) null. Add the required attribute so an empty value returns { required: true }.
Exercise
A signup field uses required and minlength="8". The user types abc. Which keys are in errors, and how do you show the number 8 in the message without hard-coding it?
Show answer
Only minlength is present, because the value is not empty so required passes. Read the number from errors?.['minlength'].requiredLength, which is 8, and use it in the message text.