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 talk about validate 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 character long” and of course if the user inputs more than 50 characters we will return “The field must be at shorter than 50 character“. 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 download from a CDN (code.angularjs.org), but you can decide to download and use it locally.

        

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 implement the ng-messages directive on the view file. Let’s see immediately an example and then I’ll explain it.

The Event Name is required
Please enter an Event Name at least 3 chars long
The Event Name entered cannot be longer than 50 chars

Focus on lines from 10 to 14. At line 10 we are using the ng-messages directive as an attribute, but you can use 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 liste at line 11, 12 and 13. Note that at line 10 we have ng-messages (plural), and at line 11,12and 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 directives allows us to define a template to use as 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:

  

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.

We can immediately see the difference from the previous usage: at line 5 there isn’t the messages list but there is a reference to the template. In fact using the attribute “ng-messages-include” we are saying to Angular to use the “error-messages” messages template.
In case the default template is not specific enough it is possible 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) :

This is my own required message

Thanks to have arrived until the end of the post and I hope that this post helps you to solve a problem or just teaches you something new. And remember: comment and suggestions are always welcome!

Subscribe to our newswletter to obtain an extra discount on the full price on the video tutorial


This post is taken from our complete course AngularJS for the Real World – Learn by creating a WebApp. Take a look and give us a feedback!

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 est.

2018-11-10T10:36:04+00:00