AngularJS Tutorial – Validation 101: ng-messages
If you are a visual learner take a look at the video below which covers the topics outlined in the post.
In previous posts of this series about AngularJS tutorial we’ve talked about validating a form using ng-class, ng-pattern, to prevent invalid data submission and to deal with form and field statuses. In this post, I’d like to approach a new module introduced in Angular 1.3 that allows us to show better messages in case of invalid data submission by the user. I’m talking about the ng-messages directive.
I want to explain better what I mean when I say “ show better messages” with an example: think about a field in a form that has many validation rules, for example a name field. We can decide that the name field is required and that it must have a 3 to 50 characters length; so we have three different rules to apply: required, min length, and max length. With ng-messages we will be able to give the appropriate message when required: if the field is not filled we will return the message: “ The field is required“, if the name is 2 chars long we will return: “ The field must be at least 3 characters long” and of course if the user inputs more than 50 characters we will return “ The field must be shorter than 50 characters“. The appropriate message for each validation rule.
Now that we understand what the directive actually does, let me explain how it works. ng-messages actually listens on a property of the ng-model that every object has, $error, showing and hiding messages based on that. Don’t worry if it sounds a bit difficult to understand, you will see an illustrative example soon.
Although ng-messages is part of the AngularJS core, it is not included in the main library and is distributed as a separate module and we have to include it in the index.html page. In the snippet below, you can see, at line 5, the inclusion of the script that is downloaded from a CDN ( code.angularjs.org), but you can decide to download and use it locally.
<script src="https://code.angularjs.org/1.3.0/angular-messages.min.js"></script>
The second step required is the injection of the dependency module into the app. The following code is the whole app.js file and you can see at the first line the inclusion of the “ ngMessages” module.
angular.module('eventApp', ['ngRoute','ngMessages'])
.config(['$routeProvider','$locationProvider',function($routeProvider, $locationProvider) {
$routeProvider.when('/add-event', {
templateUrl:'views/add-event.html',
controller: 'formCtrl',
controllerAs:'eventCtl'
})
.when('/event-list', {
templateUrl:'views/event-list.html',
controller: 'eventManagerCtrl',
controllerAs:'managerCtl'
})
.otherwise({redirectTo:'/'});
$locationProvider.html5Mode(true);
}]);
Now we have the required operation done and we can start implementing the ng-messages directive on the view file. Let’s see immediately an example and then I’ll explain it.
<form name="addEventForm">
<input type="text" name="eventName" ng-model="event.name" ng-required="true" ng-minlength="3" ng-maxlength="50" ng-messages="addEventForm.eventName.$error">
<div ng-messages="addEventForm.eventName.$error">
<div ng-message="required">The Event Name is required</div>
<div ng-message="minlength">Please enter an Event Name at least 3 chars long</div>
<div ng-message="maxlength">The Event Name entered cannot be longer than 50 chars</div>
</div>
</form>
Focus on lines from 10 to 14. At line 10 we are using the ng-messages directive as an attribute, but you can use it as an element too, to define the ng-model to listen to: “addEventForm.eventName.$error”. In this way the ng-messages loops on the $error and shows (or hides) the messages listed at lines 11, 12, and 13. Note that at line 10 we have ng-messages (plural), and at lines 11, 12, and 13 we have ng-message (singular). How does it match the message to the validation rule? Simple: the “ng-message='required'” (line 11) matches the required attribute at line 9, the “minlength” (line 12) and “maxlength” (line 13) match the “ng-minlength” and “ng-maxlength” at line 9.
The ng-messages directive allows us to define a template to use as the default set of messages. In order to use this feature, we have to define the set of messages inside a script. Let’s see how:
<script type="text/ng-template" id="error-messages">
<div ng-message="required">This is my own required message</div>
</script>
Note the two attributes of the tag script, the “ type” is set to “ text/ng-template” and the “ id” is set to an arbitrary value that we will use to reference the template in the code. In the next snippet, you can see how to use the template.
<form name="addEventForm">
<input type="text" name="eventName" ng-model="event.name" ng-required="true" ng-minlength="3" ng-maxlength="50" ng-messages-include="error-messages">
</form>
In case the default template is not specific enough it is possible to add a new message or to override one or more messages like in the example below (note at line 5 the override of the “ required” message):
<form name="addEventForm">
<input type="text" name="eventName" ng-model="event.name" ng-required="true" ng-minlength="3" ng-maxlength="50" ng-messages-include="error-messages">
<div ng-messages="addEventForm.eventName.$error">
<div ng-message="required">This is my own required message</div>
</div>
</form>
Thanks for arriving until the end of the post and I hope that this post helps you solve a problem or just teaches you something new. And remember: comments and suggestions are always welcome!
Unsorted list
- Lorem ipsum dolor sit amet, consetetur sadipscing elitr
- At vero eos et accusam et justo duo dolores et ea rebum
- Justo duo dolores et ea rebum. Stet clita kasd
- Magna aliquyam erat, sed diam voluptua at vero eos et accus
- Invidunt ut labore et dolore magna aliquyam erat, sed diam
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonu eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed di voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam et, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus.