Form validation with Angular Formly

Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 9 months ago

Every serious form has some field validation. In this lesson we're implementing some form validation with Formly and we'll learn different ways to specify and customize the validation error message.

Instructor: [0:00] Form validation is an integral part of every real-world form. Even in this case here in our example, what we would like to have for instance is whenever I remove that first name value, that usually get some message that this field is required.

[0:14] In Formly, there are already some built-in validators. We can simply activate them by going to the template options of the corresponding field -- in this case, our first name -- and here, entering required true for instance.

[0:27] As a result, what you can see is we get this * beneath our first name label which already indicates the user this field is required. Even more, if I remove here the value, you can see that it gets red.

[0:39] There's another thing which we definitely want to do. We want to obviously provide some message to the user. What we can do here is we go to the corresponding module where we have to find our Formly module for root. This Formly module for root takes an object with some additional configuration. One of them is the validation messages.

[1:00] Inside here, we can provide an array for messages that are globally valid. They're not specific to a given field on a given form, but they are generally true for our entire application. This definitely is the case for a required validator.

[1:15] For instance, what we have to do here is we have to tell Formly what kind of validator this message should be activated for and then, we give it the message. In this case, let's simply say this field is required.

[1:28] If I go back here and I remove here again that value, you can see that the model validation message gets properly displayed just below our field.