{ "id": "guide/form-validation", "title": "Validating form input", "contents": "\n\n\n
You can improve overall data quality by validating user input for accuracy and completeness.\nThis page shows how to validate user input from the UI and display useful validation messages,\nin both reactive and template-driven forms.
\nPrerequisites
\nBefore reading about form validation, you should have a basic understanding of the following.
\nTypeScript and HTML5 programming.
\nFundamental concepts of Angular app design.
\nBasics of either Template-driven Forms or Reactive Forms.
\nGet the complete example code for the reactive and template-driven forms used here to illustrate form validation.\nRun the
To add validation to a template-driven form, you add the same validation attributes as you\nwould with native HTML form validation.\nAngular uses directives to match these attributes with validator functions in the framework.
\nEvery time the value of a form control changes, Angular runs validation and generates\neither a list of validation errors that results in an INVALID status, or null, which results in a VALID status.
\nYou can then inspect the control's state by exporting ngModel
to a local template variable.\nThe following example exports NgModel
into a variable called name
:
Notice the following features illustrated by the example.
\nThe <input>
element carries the HTML validation attributes: required
and minlength
. It\nalso carries a custom validator directive, forbiddenName
. For more\ninformation, see the Custom validators section.
#name=\"ngModel\"
exports NgModel
into a local variable called name
. NgModel
mirrors many of the properties of its underlying\nFormControl
instance, so you can use this in the template to check for control states such as valid
and dirty
. For a full list of control properties, see the AbstractControl\nAPI reference.
The *ngIf
on the <div>
element reveals a set of nested message divs
\nbut only if the name
is invalid and the control is either dirty
or touched
.
Each nested <div>
can present a custom message for one of the possible validation errors.\nThere are messages for required
, minlength
, and forbiddenName
.
To prevent the validator from displaying errors before the user has a chance to edit the form, you should check for either the dirty
or touched
states in a control.
In a reactive form, the source of truth is the component class.\nInstead of adding validators through attributes in the template, you add validator functions directly to the form control model in the component class.\nAngular then calls these functions whenever the value of the control changes.
\nValidator functions can be either synchronous or asynchronous.
\nSync validators: Synchronous functions that take a control instance and immediately return either a set of validation errors or null
. You can pass these in as the second argument when you instantiate a FormControl
.
Async validators: Asynchronous functions that take a control instance and return a Promise\nor Observable that later emits a set of validation errors or null
. You can\npass these in as the third argument when you instantiate a FormControl
.
For performance reasons, Angular only runs async validators if all sync validators pass. Each must complete before errors are set.
\nYou can choose to write your own validator functions, or you can use some of Angular's built-in validators.
\nThe same built-in validators that are available as attributes in template-driven forms, such as required
and minlength
, are all available to use as functions from the Validators
class.\nFor a full list of built-in validators, see the Validators API reference.
To update the hero form to be a reactive form, you can use some of the same\nbuilt-in validators—this time, in function form, as in the following example.
\n\nIn this example, the name
control sets up two built-in validators—Validators.required
and Validators.minLength(4)
—and one custom validator, forbiddenNameValidator
. (For more details see custom validators below.)
All of these validators are synchronous, so they are passed as the second argument. Notice that you can support multiple validators by passing the functions in as an array.
\nThis example also adds a few getter methods. In a reactive form, you can always access any form control through the get
method on its parent group, but sometimes it's useful to define getters as shorthand for the template.
If you look at the template for the name
input again, it is fairly similar to the template-driven example.
This form differs from the template-driven version in that it no longer exports any directives. Instead, it uses the name
getter defined in the component class.
Notice that the required
attribute is still present in the template. Although it's not necessary for validation, it should be retained to for accessibility purposes.
The built-in validators don't always match the exact use case of your application, so you sometimes need to create a custom validator.
\nConsider the forbiddenNameValidator
function from previous reactive-form examples.\nHere's what the definition of that function looks like.
The function is a factory that takes a regular expression to detect a specific forbidden name and returns a validator function.
\nIn this sample, the forbidden name is \"bob\", so the validator will reject any hero name containing \"bob\".\nElsewhere it could reject \"alice\" or any name that the configuring regular expression matches.
\nThe forbiddenNameValidator
factory returns the configured validator function.\nThat function takes an Angular control object and returns either\nnull if the control value is valid or a validation error object.\nThe validation error object typically has a property whose name is the validation key, 'forbiddenName'
,\nand whose value is an arbitrary dictionary of values that you could insert into an error message, {name}
.
Custom async validators are similar to sync validators, but they must instead return a Promise or observable that later emits null or a validation error object.\nIn the case of an observable, the observable must complete, at which point the form uses the last value emitted for validation.
\n\nIn reactive forms, add a custom validator by passing the function directly to the FormControl
.
In template-driven forms, add a directive to the template, where the directive wraps the validator function.\nFor example, the corresponding ForbiddenValidatorDirective
serves as a wrapper around the forbiddenNameValidator
.
Angular recognizes the directive's role in the validation process because the directive registers itself with the NG_VALIDATORS
provider, as shown in the following example.\nNG_VALIDATORS
is a predefined provider with an extensible collection of validators.
The directive class then implements the Validator
interface, so that it can easily integrate\nwith Angular forms.\nHere is the rest of the directive to help you get an idea of how it all\ncomes together.
Once the ForbiddenValidatorDirective
is ready, you can add its selector, appForbiddenName
, to any input element to activate it.\nFor example:
Notice that the custom validation directive is instantiated with useExisting
rather than useClass
. The registered validator must be this instance of\nthe ForbiddenValidatorDirective
—the instance in the form with\nits forbiddenName
property bound to “bob\".
If you were to replace useExisting
with useClass
, then you’d be registering a new class instance, one that doesn’t have a forbiddenName
.
Angular automatically mirrors many control properties onto the form control element as CSS classes. You can use these classes to style form control elements according to the state of the form.\nThe following classes are currently supported.
\n.ng-valid
.ng-invalid
.ng-pending
.ng-pristine
.ng-dirty
.ng-untouched
.ng-touched
In the following example, the hero form uses the .ng-valid
and .ng-invalid
classes to\nset the color of each form control's border.
A cross-field validator is a custom validator that compares the values of different fields in a form and accepts or rejects them in combination.\nFor example, you might have a form that offers mutually incompatible options, so that if the user can choose A or B, but not both.\nSome field values might also depend on others; a user might be allowed to choose B only if A is also chosen.
\nThe following cross validation examples show how to do the following:
\nThe examples use cross-validation to ensure that heroes do not reveal their true identities by filling out the Hero Form. The validators do this by checking that the hero names and alter egos do not match.
\nThe form has the following structure:
\nNotice that the name
and alterEgo
are sibling controls.\nTo evaluate both controls in a single custom validator, you must perform the validation in a common ancestor control: the FormGroup
.\nYou query the FormGroup
for its child controls so that you can compare their values.
To add a validator to the FormGroup
, pass the new validator in as the second argument on creation.
The validator code is as follows.
\nThe identity
validator implements the ValidatorFn
interface. It takes an Angular control object as an argument and returns either null if the form is valid, or ValidationErrors
otherwise.
The validator retrieves the child controls by calling the FormGroup
's get method, then compares the values of the name
and alterEgo
controls.
If the values do not match, the hero's identity remains secret, both are valid, and the validator returns null.\nIf they do match, the hero's identity is revealed and the validator must mark the form as invalid by returning an error object.
\nTo provide better user experience, the template shows an appropriate error message when the form is invalid.
\nThis *ngIf
displays the error if the FormGroup
has the cross validation error returned by the identityRevealed
validator, but only if the user has finished interacting with the form.
For a template-driven form, you must create a directive to wrap the validator function.\nYou provide that directive as the validator using the NG_VALIDATORS
token, as shown in the following example.
You must add the new directive to the HTML template.\nBecause the validator must be registered at the highest level in the form, the following template puts the directive on the form
tag.
To provide better user experience, we show an appropriate error message when the form is invalid.
\nThis is the same in both template-driven and reactive forms.
\nAsynchronous validators implement the AsyncValidatorFn
and AsyncValidator
interfaces.\nThese are very similar to their synchronous counterparts, with the following differences.
validate()
functions must return a Promise or an observable,first
, last
, take
, or takeUntil
.Asynchronous validation happens after the synchronous validation, and is performed only if the synchronous validation is successful.\nThis check allows forms to avoid potentially expensive async validation processes (such as an HTTP request) if the more basic validation methods have already found invalid input.
\nAfter asynchronous validation begins, the form control enters a pending
state. You can inspect the control's pending
property and use it to give visual feedback about the ongoing validation operation.
A common UI pattern is to show a spinner while the async validation is being performed. The following example shows how to achieve this in a template-driven form.
\nIn the following example, an async validator ensures that heroes pick an alter ego that is not already taken.\nNew heroes are constantly enlisting and old heroes are leaving the service, so the list of available alter egos cannot be retrieved ahead of time.\nTo validate the potential alter ego entry, the validator must initiate an asynchronous operation to consult a central database of all currently enlisted heroes.
\nThe following code create the validator class, UniqueAlterEgoValidator
, which implements the AsyncValidator
interface.
The constructor injects the HeroesService
, which defines the following interface.
In a real world application, the HeroesService
would be responsible for making an HTTP request to the hero database to check if the alter ego is available.\nFrom the validator's point of view, the actual implementation of the service is not important, so the example can just code against the HeroesService
interface.
As the validation begins, the UniqueAlterEgoValidator
delegates to the HeroesService
isAlterEgoTaken()
method with the current control value.\nAt this point the control is marked as pending
and remains in this state until the observable chain returned from the validate()
method completes.
The isAlterEgoTaken()
method dispatches an HTTP request that checks if the alter ego is available, and returns Observable<boolean>
as the result.\nThe validate()
method pipes the response through the map
operator and transforms it into a validation result.
The method then, like any validator, returns null
if the form is valid, and ValidationErrors
if it is not.\nThis validator handles any potential errors with the catchError
operator.\nIn this case, the validator treats the isAlterEgoTaken()
error as a successful validation, because failure to make a validation request does not necessarily mean that the alter ego is invalid.\nYou could handle the error differently and return the ValidationError
object instead.
After some time passes, the observable chain completes and the asynchronous validation is done.\nThe pending
flag is set to false
, and the form validity is updated.
By default, all validators run after every form value change. With synchronous validators, this does not normally have a noticeable impact on application performance.\nAsync validators, however, commonly perform some kind of HTTP request to validate the control. Dispatching an HTTP request after every keystroke could put a strain on the backend API, and should be avoided if possible.
\nYou can delay updating the form validity by changing the updateOn
property from change
(default) to submit
or blur
.
With template-driven forms, set the property in the template.
\nWith reactive forms, set the property in the FormControl
instance.