You are on page 1of 28

Header

Microsoft Virtual Academy

Mastering Angular, Part 7


Custom Form Validation
Eric W. Greene

Produced by
• What is Custom Form Validation?
• Validator Functions and Directives
• Getting Started with Angular
• Demo: Setting Up the Angular Starter Application
• Validator Functions
• Demo: Creating a Custom Telephone Validator Function
• Applying Validators with a Directive
• Demo: Using a Directive to Apply the Telephone Validator
• Creating Custom Asynchronous Validators
• Demo: Validate a Book Id on the Server
• Applying a Custom Asynchronous Validator with a Directive
• Demo: Apply the Book Id Validator with a Directive
• Validating a Model Group
• Demo: Geocoding an Address
• Angular Forms and the built-in validators are very helpful for creating
forms and validating them
• In many situations though, more customized validation is needed
• Angular Forms support the creation of custom validators
• Custom validators can work synchronously or asynchronously
• Synchronous validators use logic and data already loaded in the client to
perform validations
• Asynchronous validators can access network resources to validate data
on the server
• Custom validators are written as functions
• Custom validator functions can be wrapped in directives and applied as
directives to template forms
• Custom validators can be applied on controls and form groups
• Custom validators can utilize Angular services to help validate controls
• Angular applications require some initial project configuration to get up
and running
• There are many ways to get started
• Angular CLI
• Numerous Starter Projects
• From Scratch
• This course will use a starter project configured with WebPack 2
• The WebPack development server will serve the web pages, and
WebPack will bundle the application files
• The initial starter project can be downloaded from GitHub
• Git is not required, simply fire up a web browser, and visit the following
link
• https://github.com/training4developers/mastering-angular-starter
• In the demonstration we will download, configure and fire up the project
Demo
Setting Up the Angular Starter Application
Validator Functions

• Validator functions are very easy to code


• Typically, they are coded as an arrow function and accept one parameter
of type AbstractControl, although the types FormControl and
FormGroup may be used
• The function accesses the control, performs some logic on the control's
value, then returns either null or an object
• Null means the validation PASSED
• An object with a property means the validation FAILED
• The property can be assigned any value
Validator Functions

• The return object will be mixed into the errors property of the form
control object
• The form control's errors object can then be used to update the UI with
information about what failed
• If additional information is provided on the object returned from the
validator object, that information is available on the errors object
through the property set by the validator
• A common use for additional information is identify specific errors in a
complex validation
Validator Functions

• A failed result from the validator object will result in the control, group
or form being updated with the ng-invalid class
• Once the validator passes (after the user corrects any errors), the ng-
invalid class will be removed and replaced with ng-valid
Validator Functions

• When working with validator functions, they are only useful with
Reactive (aka Model-Driven) forms
• To apply a validator function to a template form control, group or form,
it must be wrapped in a directive (covered in the next section)
• Final note, these validator functions are known as synchronous validator
functions, in the second half of the course, asynchronous validators will
be covered
Demo
Creating a Custom Telephone Validator Function
• To use custom validator functions with template forms, they must be
wrapped in a directive
• To implement the directive, the custom validator needs to be added to
the NG_VALIDATORS multi-provider, and a selector needs to configured
• Multi-providers allow multiple services to be injected for a single
injection token
• For validators, there are two multi-providers, NG_VALIDATORS and
NG_ASYNC_VALIDATORS
• The multi-providers are an array of validators
• In addition to the multi-provider configuration, a selector needs to be
specified
• Some examples include:
• [type=tel][ngModel] – apply the validator to elements with NgModel
and of type telephone
• [ssn][formControl] – apply the validator to elements with the
formControl and the ssn attributes (yes, validator directives can be
used with reactive forms)
• form[address] – apply the address validator to forms with an address
attribute
Demo
Using a Directive to Apply the Telephone Validator
Creating Custom Asynchronous Validators

• Commonly, user entered data needs to be validated on the server


• Perhaps, the validation algorithms are proprietary, or the data sets are
huge, then validating on the client is not an option
• To accommodate this situation, Angular provides asynchronous
validators
• Asynchronous Validator functions are exactly the same as a Synchronous
Validator functions except they return a Promise or Observable instead
of an object
• When the Promise or Observable resolves, it will output the same kind
of object result as a synchronous validator
Creating Custom Asynchronous Validators

• Asynchronous Validators can be applied to control, groups and the form


element itself
• Asynchronous Validators do not always execute
• If all of the synchronous validators for any control, group or form pass,
and the control, group or form has an asynchronous validator, then that
asynchronous validators and all others will be invoked
• The execution timing is a little confusing to think about
• For example, if a control has an asynchronous validator, and it's
synchronous validators all pass, not only will it's asynchronous validator
execute, but all asynchronous validators on other controls, groups and
the form will execute
Creating Custom Asynchronous Validators

• When the asynchronous validator is executing, the class ng-pending


will be applied to the form elements, and styling can be done to signify
that an asynchronous operation is occurring
Demo
Validate a Book Id on the Server
Custom Asynchronous Validator Directive

• Using an approach similar to applying a synchronous validators with a


directive, asynchronous validator can be used
• One challenging aspect working with asynchronous validators is that
they typically depend upon other Angular services for performing their
asynchronous operations such as AJAX calls
• While synchronous validators can require other services too, the method
of injecting services into both kinds of validator directives will be
covered here
Custom Asynchronous Validator Directive

• There are two primary approaches to injecting services into a directive


for a validator (synchronous and asynchronous)
• First, when configuring the validator service provider, a factory function
and deps may be specified
• Second, the needed services can be injected via the directive's
constructor, then within the constructor, the validator function can be
initialized with the injected services. For this to work, the providers
validator configuration in the directive class will need to be configured
with useExisting and the forwardRef function
Custom Asynchronous Validator Directive

• Which approach is better? It depends upon preferences


• Both work equally well. Some consider the first approach too verbose,
others consider the second approach too complicated
• Both approaches will be demonstrated for this course
Demo
Apply the Book Id Validator with a Directive
• Validation is typically thought of in terms of validating a specific control
• Nevertheless, its common to validate the combined data of many
controls
• With form group validation this is possible
• Form Groups are defined imperatively with the FormGroup class, and
declaratively with NgForm and NgModelGroup
• When using ViewChild or template reference variable to access the
FormGroup object on NgForm and NgModelGroup it's available
through the control property
• When validating groups, the group itself may have its own synchronous
and asynchronous validation functions
• The overall validation status of the group is aggregated from its children
as well as the results of its own validators
• A group is only valid if all of its children are valid, and its own validators
pass
Demo
Geocoding an Address
• In this course, custom validators were explored
• Synchronous and Asynchronous validator functions and directives were
created
• Service injection with respect to validator directives was explained
• Validating groups of controls was coded as well
• Some interesting validators performing phone number validation,
information lookup and geocoding were demonstrated
• For more information on reactive forms, template forms, built-in form
validators, please check out the other videos on forms in this series

You might also like