Select Page

Regex Input Validation with NG-Pattern

Posted on August 3, 2017
James Quick, Social Developer

Often, when taking user input, we need to validate that the user is entering data in a certain format.  When taking email addresses, for example, you want to make sure what they enter matches the format of an email address (ex.  Anytime, as a developer, you come across a situation where you need to enforce pattern matching, Regex (Regular Expression) should be the first thing that comes to mind.

Regex is something that I’ve understand the theory behind for a while now, but almost always have to lookup correct syntax.  Regardless, it gives us the ability to match a any specified pattern… any email address (, a phone number (ex. 111-111-1111), a date (ex. mm-dd-yyy), etc. .  As I’m writing this, I;m realizing that a deeper post on how to use Regex in Javascript would be helpful, so keep an out for that!  For now, I just want to show how to use ng-pattern to add pattern validation to user input.  This assumed you understand the basics of Regex.

I’ll post the link to the code pen, and then explain.

See the Pen Angular NG-Pattern by James Quick (@jamesqquick) on CodePen.0


Go ahead and have a look.  The HTML for this example should be pretty straightforward.  The key is the use of the ng-pattern directive.  It’s worth it to note that there exists a ‘pattern’ tag in regular HTML that allows us to enter a pattern directly and accomplish the same validation.  However, ng-pattern (as with other Angular directives) allows us to define the pattern in the controller (with a variable on the $scope) as well as directly in the HTML.  Here to show that ng-pattern can do both, we’ve got two different inputs, one defines the pattern directly and the other uses a variable in the controller.

The pattern that I’ve defined allows the user to enter uppercase and lowercase letters as well as numbers.  Patterns can get immensely more complex, but for our purposes, I think this example suffices.  If you have any experience with Angular, this should have been really easy to follow.  If you were like me, and originally just didn’t know the ng-pattern existed, then hopefully this helped!

If you suggestions on specifics aspects of Regex that are trickier and you would like to see a post on, let me know!! @jamesqquick




Javascript. Node. Angular. Bootstrap. Wordpress. You name it.  If you are a current or aspiring web developer looking to learn more, then subscribe!  I will share the latest news and tutorials as well as exclusive assets.

Thank you for subscribing!

Pin It on Pinterest

Share This

Share this post with your friends!