Asynchronous Validation With Angular Reactive Forms

  • the debounceTime() operator makes sure that only the latest value is passed through after 500ms have passed without a value change
  • When all the synchronous validators are valid the asynchronous validators run on every keyup.
  • the filter() operator makes sure that values are only passed through when they have 2 characters or more
  • inputField exposes the aforementioned Observable property .valueChanges() which is a stream of value changes of that input field.
  • Synchronous validators of a form element always run when a keyup event happens on that element.

The Reactive Forms Module in Angular allows you to add synchronous and asynchronous validators to form elements. Synchronous validators of a form element always run when a keyup event happens on that…

@SitePointJS: Asynchronous Validation With Angular Reactive Forms #AngularJS

The Reactive Forms Module in Angular allows you to add synchronous and asynchronous validators to form elements. Synchronous validators of a form element always run when a keyup event happens on that element.

When all the synchronous validators are valid the asynchronous validators run on every keyup. And there is no easy way to debounce them at this point in time.

I find this surprising since asynchronous validation mostly (always?) is server-side validation and you most likely don’t want to have multiple users sending a request per keyup event to the server.

In order to lighten the server load you would want to filter and debounce the values that are put into a form field by the user. This can be easily done via RxJS operators if you get access to the stream of value changes.

So how do we do that? Well, just like Pascal Precht ʕ•̫͡•ʔ said in his tweet above.

So lets say you have an input field like this:

which is a stream of value changes of that input field. We can subscribe to it like so:

This is great because with the Observable operators that come with RxJS we have really good control over under which conditions and how often we want to send validation requests to the server.

Let’s go through what the code above does:

is cool because it allows you to set specific errors on the field dynamically. Here is how it works: if you want to set an error you just call the method with an object that gives the error a name:

state, when you want to make it valid again all you do is:

Hopefully the Angular team comes up with an easier way to debounce async validators in the future, but for now, this works well.

Asynchronous Validation With Angular Reactive Forms