angular-formly: Custom Validation

Kent C. Dodds
InstructorKent C. Dodds
Share this video with your friends

Social Share Links

Send Tweet
Published 10 years ago
Updated 6 years ago

AngularJS validation can be tough, but angular-formly makes it extremely simple with a single validation API that enables basic and advanced field validation. You can specify a string expression, function that returns true/false, or a function that returns a promise which is resolved/rejected.

[00:00] Angular Formly comes with a very simple validation API. If I wanted to validate that this first name was never Bob, I would simply say validators is an object with not Bob, and we'll say view value is not equal to Bob. So if I type Bob, then we see the submit button gets disabled, and we get a red outline indicating we have an error for that field.

[00:24] If I wanted to validate this IP address, I can say validators and we'll say ipaddress, and then we'll specify a function that takes a view value, a model value, and a scope, and I'll say my value is equal to the model value or the view value, and if there is a value then I will return the validate IP address function with that value, otherwise I'll return true because this field is not required.

[00:59] Let's verify that works. So we'll say 127, we notice we now have an error. If I finish that out, then it is now valid. Finally, if I want to do something asynchronous, and give the form that handles this as well. I'll say validators is unique and this will be a function that accepts, again, a view value, model value, and a scope, and then let's emulate hitting a database and getting the values back. So we've injected timeoutage here, and we have a list of taken user names, so something that's not unique.

[01:37] We'll look at our timeout and we'll simply return timeout which returns a promise and will have that return in 1,000 milliseconds. Then let's say our value is equal to the model value or the view value, then we'll verify that this value is not taken as one of these taken user names. So we'll say if takenusernames.indexof(value) != -1, so if it's in the array, then we will throw new error not unique, else we'll simply return unique.

[02:27] The return isn't really important, what's important is that the promise that is returned from this timeout is resolved if the validation succeeds, and fails if the validation does not succeed. So if I enter in foobar, and exit here, we see that the user name foobar is set and that's because it's not one of the taken user names. But if instead I say foo, that is set and when this error is thrown, the promise is rejected and the validation fails.

[03:00] That is the validation API for Angular Formly. You specify a Formly expression which can be a string, a function that returns true or false, and a function that returns a promise that is resolved or rejected.