@title
Form Validation
@intro
Validate user's form entries.
@description
{@a top}
We can improve overall data quality by validating user input for accuracy and completeness.
In this cookbook we show how to validate user input in the UI and display useful validation messages
using first the template-driven forms and then the reactive forms approach.
Learn more about these choices in the [Forms chapter.](guide/forms)
{@a toc}
## Table of Contents
[Simple Template-Driven Forms](guide/form-validation#template1)
[Template-Driven Forms with validation messages in code](guide/form-validation#template2)
[Reactive Forms with validation in code](guide/form-validation#reactive)
[Custom validation](guide/form-validation#custom-validation)
[Testing](guide/form-validation#testing)
{@a live-example}
**Try the live example to see and download the full cookbook source code**
{@a template1}
## Simple Template-Driven Forms
In the template-driven approach, you arrange
[form elements](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms_in_HTML) in the component's template.
You add Angular form directives (mostly directives beginning `ng...`) to help
Angular construct a corresponding internal control model that implements form functionality.
We say that the control model is _implicit_ in the template.
To validate user input, you add [HTML validation attributes](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation)
to the elements. Angular interprets those as well, adding validator functions to the control model.
Angular exposes information about the state of the controls including
whether the user has "touched" the control or made changes and if the control values are valid.
In the first template validation example,
we add more HTML to read that control state and update the display appropriately.
Here's an excerpt from the template html for a single input box control bound to the hero name:
{@example 'cb-form-validation/ts/src/app/template/hero-form-template1.component.html' region='name-with-error-msg'}
Note the following:
- The `` element carries the HTML validation attributes: `required`, `minlength`, and `maxlength`.
- We set the `name` attribute of the input box to `"name"` so Angular can track this input element and associate it
with an Angular form control called `name` in its internal control model.
- We use the `[(ngModel)]` directive to two-way data bind the input box to the `hero.name` property.
- We set a template variable (`#name`) to the value `"ngModel"` (always `ngModel`).
This gives us a reference to the Angular `NgModel` directive
associated with this control that we can use _in the template_
to check for control states such as `valid` and `dirty`.
- The `*ngIf` on `
` element reveals a set of nested message `divs` but only if there are "name" errors and
the control is either `dirty` or `touched`.
- Each nested `
` can present a custom message for one of the possible validation errors.
We've prepared messages for `required`, `minlength`, and `maxlength`.
The full template repeats this kind of layout for each data entry control on the form.
#### Why check _dirty_ and _touched_?
We shouldn't show errors for a new hero before the user has had a chance to edit the value.
The checks for `dirty` and `touched` prevent premature display of errors.
Learn about `dirty` and `touched` in the [Forms](guide/forms) chapter.The component class manages the hero model used in the data binding
as well as other code to support the view.
{@example 'cb-form-validation/ts/src/app/template/hero-form-template1.component.ts' region='class'}
Use this template-driven validation technique when working with static forms with simple, standard validation rules.
Here are the complete files for the first version of `HeroFormTemplateCompononent` in the template-driven approach:
{@example 'cb-form-validation/ts/src/app/template/hero-form-template1.component.html'}
{@example 'cb-form-validation/ts/src/app/template/hero-form-template1.component.ts'}
{@a template2}
## Template-Driven Forms with validation messages in code
While the layout is straightforward,
there are obvious shortcomings with the way we handle validation messages:
* It takes a lot of HTML to represent all possible error conditions.
This gets out of hand when there are many controls and many validation rules.
* We're not fond of so much JavaScript logic in HTML.
* The messages are static strings, hard-coded into the template.
We often require dynamic messages that we should shape in code.
We can move the logic and the messages into the component with a few changes to
the template and component.
Here's the hero name again, excerpted from the revised template ("Template 2"), next to the original version:
{@example 'cb-form-validation/ts/src/app/template/hero-form-template2.component.html' region='name-with-error-msg'}
{@example 'cb-form-validation/ts/src/app/template/hero-form-template1.component.html' region='name-with-error-msg'}
The `` element HTML is almost the same. There are noteworthy differences:
- The hard-code error message `` are gone.
- There's a new attribute, `forbiddenName`, that is actually a custom validation directive.
It invalidates the control if the user enters "bob" anywhere in the name ([try it](guide/form-validation#live-example)).
We discuss [custom validation directives](guide/form-validation#custom-validation) later in this cookbook.
- The `#name` template variable is gone because we no longer refer to the Angular control for this element.
- Binding to the new `formErrors.name` property is sufficent to display all name validation error messages.
#### Component class
The original component code stays the same.
We _added_ new code to acquire the Angular form control and compose error messages.
The first step is to acquire the form control that Angular created from the template by querying for it.
Look back at the top of the component template where we set the
`#heroForm` template variable in the `