Lesson 19 / 30
Form Validation
Enforce rules and show errors to the user.
Built-in validators
Pass validator functions when creating a FormControl — Validators.required, Validators.email, Validators.minLength, and more.
form = new FormGroup({
email: new FormControl('', [Validators.required, Validators.email]),
password: new FormControl('', [Validators.required, Validators.minLength(8)]),
});Showing errors
Check a control's invalid and touched state to show an error only after the user has interacted with the field.
<input formControlName="email">
@if (form.controls.email.invalid && form.controls.email.touched) {
<small>Enter a valid email.</small>
}Quick check: Where do you attach validators to a reactive form control?
- As an attribute in the HTML template
- As the second argument when creating the FormControl
- Inside the component's constructor only
Answer
As the second argument when creating the FormControl — `new FormControl('', [Validators.required])` passes validators directly to the control.