Explicit AngularJS Input Validation using ngPattern and Regex

Posted by

Recently I ran into an issue where I needed to have input validation on an HTML form, specifically for validating a date input and an email input. Naturally, my first thought is to use whatever is built in to the language, so the idea was to use specific HTML input types. However, there were issues that arose in testing this, one of which being that there was no “.com” email ending validation (meaning you could enter “user@email”and it would pass validation). This may be fine for some scenarios, but in my use case, it was a hard set requirement to have the “.com” ending validated as well.

The way to do this is to utilize ngPattern. This attribute takes in a regular expression (regex) and checks for a match on the input. That match check is then emitted through the form input’s $error object, specifically as “pattern”. Below is an example of a few use cases of ngPattern to validate a specific date input and a specific email input, along with an example of using UI Bootstrap’s datepicker, and how it differs. Note that the $error is displayed in parenthesis, and as you change the entered text, “pattern” gets set to true.

 

While this might not be the best approach for handling form validation, if you need to specify an explicit format for an input, using ngPattern and regex proves to be very effective.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.