Angular Forms and ngMessages

I’ve been working with forms in AngularJS for quite sometime, and since I started using ng-messages, I’ve hated the fact that I have to copy and paste all those blocks of validation messages code over and over again.

The moment you realize that you’re copying and pasting code, that’s when you know that something’s wrong.

So my idea was to add those blocks dynamically. But those blocks have ng-message directives inside of them and you can’t just add them to the DOM. First, you have to compile them..

So after some digging into the official documentation, turns out that AngularJS provides a service called $compile.

So, by compiling the block that contains the validation code and appending it right after the input tags. We can automate that tedious task!

I’ve made this helper directive that you apply on your form and it does that automatically for you. It’s heavily dependent on bootstrap’s form structure. So you have a div with a class of form-group that contains a label and an input tag. And all those form-groups are wrapped in a form. You just add the validate-this-form directive to your form and everything is done automatically for you.

Supporting most standard input types.

I’ve also made it support some UI-Bootstrap’s components. Of course, the implementation of every form input type is tedious, so it’s best if you just fork the repository and apply your own validation there.

My GitHub repository is right there, if you want to check it out. You can bower install it, or download it directly and tinker with it. I appreciate any feedback or contributions to the repository.

Some examples and goodies could be found here.