Leonardo PΓ©rez M

Front End Developer

@YuxiGlobal
Β 

Passionate about
  • CSS
  • Technology
  • Watch sports 
@leono286

Custom async validator in Angular forms

Quick review

Two flavors

  • Template driven forms

Β 

  • Reactive forms

Template driven forms

<input>

Class

property

[(ngModel)]

Template driven forms

😎

Reactive forms

<input>

Class

property

[formGroup]

[formControl]

Reactive forms

😊

Reactive forms

😎

formBuilder.control(...)

Reactive forms

Custom Validators

πŸ•΅οΈβ€β™€οΈπŸ•΅οΈβ€β™‚οΈ

Custom Validators

Validator

Function

Sync

{

Async

AsyncValidatorFn =

(FormControl | FormGroup):

 Promise<null | ValidationErrors>
 Observable<null | ValidationErrors>

Custom Validators

Async

ValidationErrors = {

    [key: string]: any;

}

Custom Validators

{'nameTooUgly': true}

Async

Custom Validator

πŸ±β€πŸ‘€β°

  • Create ValidatorFn as a service method
    Β 
  • Wrap ValidatorFn in directive (template driven)
    Β 
  • Implement validator in form

Async Custom Validator

Async Custom Validator

Create ValidatorFn as service method

Import what we need

Async Custom Validator

Import what we need

Async Custom Validator

Set up the service and inject github service

Async Custom Validator

Implement validate method

Async Custom Validator

Implement validate method

Async Custom Validator

RxJS helpers to delay requests to github API

Async Custom Validator

Get current value in form control

Async Custom Validator

Call github API using the injected github serviceΒ 

Async Custom Validator

Make the validation itself

Async Custom Validator

Return the validation outcome

Async Custom Validator

Async Custom Validator

Wrap ValidatorFn (service method) with directive

Async Custom Validator

(template driven)

Import what we need

Async Custom Validator

Import what we need

Async Custom Validator

Set up directive metadata

πŸ•΅οΈβ€β™‚οΈ

Async Custom Validator

Inject validator service in directive's constructor

Async Custom Validator

Set the directive's validate method to be the ValidatorFn

(usernameValidator service method)

Async Custom Validator

Set the directive's validate method to be the ValidatorFn

(usernameValidator service method)

Async Custom Validator

Implement async custom validator in form

Template

driven

Reactive

Directive

FormBuilder

Async Custom Validator

πŸ±β€πŸ‘€

Whit custom validator

Template driven form

Async Custom Validator

😎

Reactive form

With custom validator

Async Custom Validator

πŸ±β€πŸ‘€

Inject our validator service

formBuilder.control(...)

Reactive forms

Reactive form

What we had before

😎

Async Custom Validator

πŸ±β€πŸ‘€

Async Custom Validator

Reactive form

With custom validator

😎

That's it!!

Async Custom Validator

Demo time!!

Async Custom Validator

Cross field validation

Example repo

Thanks!!

Angular rocks!!

Custom async validator for Angular forms

By Leo Perez

Custom async validator for Angular forms

  • 3