AngularJS Tutorial – Validation 101: Useful Directives

Useful directives for conditionally formatting and track fields min and max length

  • ng-show ng-hide directives

If you are a visual learner take a look at the video below which covers the topics outlined in the post

In this AngularJS Tutorial we’ll see what ng-show and ng-hide directive do, and they do exactly what the name suggests: show and hide. Moreover we’ll see other two foundamental directives to validate our data: ng-minlength and ng-maxlength


ng-show & ng-hide

Let’s jump in directly to ng-show/ng-hide. We can use them to show and hide objects in the page without applying CSS rules or JavaScript: in fact we let AngularJS do the hard work for us. And now we will see how.

As you can see at line 6 from the code above, the ng-show directive, and the ng-hide also, takes an AngularJS expression as parameter, note that the expression must return a boolean value. The directive evaluates the expression and if true shows the DOM bock, otherwise it hides the block. The ng-hide directives behaves in a manner contrary, i.e. it hides the DOM when the expression has a truthful value. The expression could be a $scope property (boolean), a $scope function (must return a boolean value) or, as shown in the example, it could be a a complex expression resulting from a multiple condition chaining.

Now you maybe asking yourself why use the ng-show/ng-hide directives if the ng-if does the same thing. Well, there’s an important difference: ng-if destroy and create the DOM objects, while the ng-show/ng-hide simply shows and hides objects and do their work adding or removing the CSS “.ng-hide” (attention: don’t confuse it with the directive).

ng-minlength & ng-maxlength

What they do: ng-minlength and ng-maxlength directives applies to form fields and they perform a length validation of the input data.

In the above example we set the minimum length to 3 and and maximum to 50 for the “eventName” field, so when filling in the event’s name if we use a text shorter than 3 chars or longer than 50 the “addEventForm.eventName.$invalid” property is set to true and the form is invalid. Note that the message at lines 13 is shown only if the form is dirty and if there are validation issues on the field.

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!


About the Author:

Viaggiatore seriale e aspirante fotografo, lavoro in ambito ICT da oltre 15 anni. Collaboro con Webyourmind sin da quando era ancora solo un'idea nella testa dei fondatori. Sono appassionato di nuove tecnologie e di tutto quello che il web offre.

0 Pings & Trackbacks

Leave a Reply

%d bloggers like this: