Check out myAngular article series with live demos and Facebook group Angular - Advanced Topics

Angular - binding validation expressions to ng-pattern

Torgeir "Tor" Helgevold
- JavaScript Developer and Blogger
Published: Mon Mar 30 2015

Angular 1.3 introduced the ability to bind validation expressions using the ng-pattern directive. Here is a quick description of how to use it.

Prior to 1.3 ng-pattern was not backed by a directive, so it could only work with hard coded expressions in the markup. This made it hard to reuse and unit test expressions since there was no way to define the actual expressions outside of the markup.

The code listing below show how to set it up:

<div ng-controller="priceController as priceController"> <input ng-model="priceController.price" ng-pattern="priceController.numericPattern" /> </div> angular.module('poc-project').controller('priceController', function(){ this.numericPattern = /[0-9]+$/; this.price = 100; } );

If you liked this article, share it with your friends on social media:

We also have a new Facebook group about advanced Angular topics.

I invite you to follow me on twitter