# Form Validation — Angular

Source: https://www.geekswithgeeks.com/en/angular/ng-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.

```typescript
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.

```html
<input formControlName="email">
@if (form.controls.email.invalid && form.controls.email.touched) {
  <small>Enter a valid email.</small>
}
```

**Quiz:** Where do you attach validators to a reactive form control?

- [ ] As an attribute in the HTML template
- [x] 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.
