include ../_util-fns a#top :marked 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. .l-sub-section :marked Learn more about these choices in the [Forms chapter.](../guide/forms.html) a#toc :marked ## Table of Contents [Simple Template-Driven Forms](#template1) [Template-Driven Forms with validation messages in code](#template2) [Reactive Forms with validation in code](#reactive) [Custom validation](#custom-validation) [Testing](#testing) a#live-example :marked **Try the live example to see and download the full cookbook source code** live-example(name="cb-form-validation" embedded img="cookbooks/form-validation/plunker.png") .l-main-section a#template1 :marked ## 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: +makeExample('cb-form-validation/ts/app/template/hero-form-template1.component.html','name-with-error-msg','template/hero-form-template1.component.html (Hero name)')(format='.') :marked 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 `