A while ago (at NDC London) I attented a two day course on Angular by the great K. Scott Allen, who spoke about using the ngMessages directive to provide re-usable validation on forms.

While ngMessages is good, there is no way of providing detail on validation failures. For example, if a text input has to be at least 5 characters long, you can provide a message saying “your entry is too short”, but not “your entry needs to be at least 5 characters”. This is frustrating for an end user, who would need to keep entering characters until they reach the unknown limit. You could hardcode the limit into the validation message for the input, but this would defeat re-usability which is one of the main benefits of ngMessages.

Therefore, I’ve come up with a directive that provides re-usable, informative validation error messages. It works with HTML validation attributes as well as custom validators. You provide a template with the error messages (much like ngMessagesInclude). This template can access the property of each validation attribute and use it to display a more informative message.

A Plunkr is available here.

To use it, add the validator.js code and ngMessages to your Angular app. Then, create a template for the error messages:

Please enter at least {{ minlength }} letters
Please do not enter more than {{ maxlength }} letters
Please enter text beginning with {{ startWith }}

N.B: the “startWith” message is for a custom validator that checks that the input starts with a particular character.

The containing div with “ng-messages” needs to be kept as is, while the inner divs containing the validation messages can be changed to your own custom message. Note the binding within each message.

Next, we can use the validator and the template on an input:

< input type="text" name="exampleTextBox" ng-model="name" minlength="5" maxlength="10" start-with="s" validator="validation-messages.html" />

In the last attribute, we specify we are using the validator and pass in the location of the template to use. Also note you must give the input a name and use ngModel for the validator to work.

Now, if we try to enter some input that is fewer than 5 characters, greater than 10 or doesn’t start with s we get a friendly error message telling us exactly what went wrong and why. If we fail more than one validation, we get a message for each failure.

The name of the binding within each message matches the name of the validation attribute, and the value it is bound to matches the property value of the attribute. So, “Please enter at least {{ minlength }} letters” for minlength=”5″ becomes “Please enter at least 5 letters”.

You can see a fully working example in the Plunkr.

Next time, I’ll go through the code for the validator directive.


Leave a Reply