If you are a visual learner take a look at the video below which covers the topics outlined in the post
Today we will talk about another AngularJS validation directive: the ng-pattern. As you can guess from its name, this directive introduces the validation through a pattern and the pattern we use is represented by a regexp.
I suppose that you already know what a regular expression (regexp) is, so I’m just providing to you some external resources to deepen the topic because I won’t go further in this post.
Here you can find useful information about regular expressions visiting: the Wikipedia page and the Mozilla Developer page.
This is the theory, now let’s take a look at the code:
Please enter the date in the yyyy-mm-dd format
In the code above (taken from the AngularJS Tutorial by Webyourmind) at line 4 you can see the ng-pattern directive with its regular expession. What we are trying to do is to check the date formatting according to the pattern yyyy-mm-dd where “yyyy” is a 4 digits and “mm” and “dd” are 2 digits long numbers.
The result of this operaton is a change in the behaviour of the form validation, i.e. the field is valid when the date is formatted according to the pattern, on the contrary the scope property “eventCtl.eventForm.date.$invalid” is set to true and the message on line 5 of the example is shown.
In order to make the validation works we must remember to change the field type from “date” to “text“: in this way the HTML does not perform the standard data validation on the field and all the work is demanded to AngularJS.
Note that in this example we are passing the parameter in the regexp format surrounded by single quotes, but if you use the string form (surrounding it by double quotes) it will be converted into a regexp: for example “abc” becomes ‘^abc$’.
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!