Angular 33: Reactive Forms Validation
easy⏱ 5 mincourseangular
Validators are the second argument to a control
new FormControl('', Validators.required) — or, with FormBuilder's array shorthand, email: ['', [Validators.required, Validators.email]] — attaches one or more validator functions to a control. Angular re-runs them on every value change and stores the result on the control.
form = this.fb.group({
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(8)]],
});
invalid + touched: don't yell at the user before they've typed
Checking form.get('email')?.invalid alone would show an error on a pristine, empty form the instant it renders. Pairing it with .touched (true once the field has been focused and blurred) delays the message until the user has actually had a chance to fill it in — a small check that makes a big usability difference.
@if (form.get('email')?.invalid && form.get('email')?.touched) {
<p class="error">Enter a valid email address.</p>
}
Inspecting exactly which validator failed
form.get('email')?.errors is an object keyed by validator name, e.g. { required: true } or { email: true }, so you can tailor the message: @if (form.get('email')?.hasError('required')) { ... } @else if (form.get('email')?.hasError('email')) { ... }.