Wednesday, March 23, 2016

How to validate an input field with Angular JS

Angular JS offers a very simple way to validate an entry into an input field with a regular expression with the ng-pattern attribute.

I had to change a behavior of an input field in an application: special characters like 'ä', 'ö', 'ü' were not allowed, but should have.

The interesting thing is that the pattern can be assigned dynamically.

Here is the setup:

for a static pattern, I use a variable (vm.regex) in my controller.

(function () {
    var valApp = angular.module("valApp", []);
    valApp.controller("ListCtrl", ListController);
    function ListController() {
        var vm = this;
        vm.regex ='\\d+';
        ...
    }
})();

... and in the view, the attribute ng-pattern references this variable: 


<div class="container" ng-app="valApp">
  <div class="row" ng-controller="ListCtrl as ctrl">
    <form name="myForm">
      <div class="span4">
          <p>
            <label>Field1:</label>
            <input name="field1" 
            type="text" 
            ng-model="ctrl.item.field1" 
            ng-pattern="'\\d'"/>
          </p>
          <p>
            <label>Field2:</label>
            <input name="field2" 
            type="text" 
            ng-model="ctrl.item.field2" 
            ng-pattern="ctrl.regex"/>
          </p>
      </div>
    </form>
  </div>
</div>

Now, the pattern to allow characters with "Umlauten" (ä,ü,ö) is as follows:

[a-zA-Z0-9öüäÖÜÄ]+