Dynamically ng-pattern use

by Stepan Kasyanenko

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="MyCtrl">
  <ng-form name="MyForm">

    <h3>
     With dynamic pattern
    </h3>
    <select ng-model="dataTypeValue" ng-options="t as t.label for t in dataTypeList" ng-change="getCustomPattern(MyForm.input)">

    </select>

    <input type="text" ng-model="textValue.text" ng-pattern="getCustomPattern(MyForm.input)" ng-model-options="{allowInvalid:true}" name="input">
    <br>
    <br>
    <br> Data type: {{dataTypeValue}}
    <br> Entered value: {{textValue}}

  </ng-form>
</div>

CSS

input.ng-invalid {
  border-color: red;
}

JavaScript

var myApp = angular.module('myApp', []);

myApp.controller("MyCtrl", function($scope) {
  var tThis = this;
  $scope.dataTypeList = [{
    'id': 1,
    "label": "Currency"
  }, {
    'id': 2,
    "label": "Number"
  }, {
    'id': 3,
    "label": "Text"
  }];
  $scope.dataTypeValue;
  $scope.textValue = {
    text: ""
  };
  $scope.customPattern = /.*/;
  var isParser = false;
  $scope.getCustomPattern = function(pInput) {
    if (!$scope.dataTypeValue)
      return $scope.customPattern;
    var dataTypeId = $scope.dataTypeValue.id;
    if (dataTypeId === 1) {
      $scope.customPattern = /^\d{1,10}$/;
    } else if (dataTypeId === 2) {
      $scope.customPattern = /^\d+$/;
    } else if (dataTypeId === 3) {
      $scope.customPattern = /^.*$/;
    }
    if (!$scope.getCustomPattern.isParser) {
      $scope.getCustomPattern.isParser = true;
      pInput.$setViewValue(pInput.$viewValue);
    } else {
      $scope.getCustomPattern.isParser = false;
    }
    return $scope.customPattern;
  };
});