Angular - binding validation expressions to ng-pattern

- 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; } );