简体   繁体   中英

Generate regular expression for ng-pattern in Angular 1.5

In Angular 1.2 it was possible to use ng-pattern as follows:

<input ng-model="myModelVar" ng-pattern="myModelRegex" />

where myModelRegex could be something like: /^[a]+$/i for a case insensitive match on a number of a 's. Since AngularJS 1.5 the behaviour has changed (as shown in their documentation: see here ).

What I want to achieve is something like:

  $scope.testRegex = '^[a]+$';

  $scope.generateRegex = function(modelVar) {
    return new RegExp(modelVar, 'i');
  }

with:

  <input ng-pattern="generateRegex(testRegex)" name="testInput3" ng-model="testVar3" />

So, my regex is actually a model variable, and is supplied by an external source. It doesn't matter that people can change it, the backend filters this as well.

The example above "works", but throws an infDigest error. See my jsFiddle: https://jsfiddle.net/t0nfurjb/

What do I need to do to fix this?

[EDIT]

So, to clarify, I do a web call, which returns me something like this:

[
{
 caption: "Please enter your mail address";
 regex: [a-z]+@[a-z]+.[a-z]+
},
{
 caption: "Please enter your phone number";
 regex: [0-9]{10}
}
]

And I want to use the provided regexes in my view.

Note: the regexes are made up on the spot and should never ever ever ever be used in actual systems.

Check this out!

 angular .module('demoApp', []) .controller('MainController', MainController) function MainController($scope) { var modelVariable; $scope.testVar = 'bb'; getRegex(); $scope.regex = new RegExp(modelVariable, 'i'); function getRegex() { // get regex via data source and set it on local variable. modelVariable = '^[b]+$'; } } 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="demoApp" ng-controller="MainController"> <form name="testForm"> <!-- What I want: --> <input ng-pattern="regex" name="testInput" ng-model="testVar" /> <input type="submit" /> <pre> input: {{testVar}} $error: {{testForm.testInput.$error}} </pre> <br /> </form> <pre> </pre> </div> 

This works too as well jsfiddle eg Angular 1.4.8 and is much simpler compared to the above one, the same eg in plnkr with Angular 1.5.5

UPDATE:

Simple example using ng-repeat directive and ng-form directive.

<!DOCTYPE html>
<html ng-app="demo">

  <head>
    <script data-require="angularjs@1.5.5" data-semver="1.5.5" src="https://code.angularjs.org/1.5.5/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
    <style>
    .margin-bottom {
      margin-bottom: 2%;
    }
    </style>
  </head>

  <body ng-controller="DefaultController as ctrl">
    <form role="form" name="heroForm" novalidate="novalidate">
      <div class="margin-bottom" ng-repeat="hero in ctrl.heroes">
        <ng-form name="heroFieldForm">
          <label>{{hero.name}}</label>
          <div>
            <label>Email:</label>
            <input type="email" name="email" ng-model="hero.email" ng-required="true" ng-pattern="ctrl.getRegex('email')"/>
            <span ng-show="heroFieldForm.email.$invalid">Valid Email Required</span>
          </div>
          <div>
            <label>Phone:</label>
            <input type="tel" name="phone" ng-model="hero.phone" ng-required="true" ng-pattern="ctrl.getRegex('phone')"/>
            <span ng-show="heroFieldForm.phone.$invalid">Valid Phone Required</span>
          </div>
        </ng-form>
      </div>
    </form>
  </body>

</html>

angular
  .module('demo', [])
  .controller('DefaultController', DefaultController);

function DefaultController() {
  var vm = this;
  vm.heroes = heroes;
  vm.regexes = regexes;
  vm.getRegex = getRegex;

  function getRegex(type) {
    if (type === 'email') {
      return vm.regexes[0].regex;
    } else {
      return vm.regexes[1].regex;
    }
  }
}

var heroes = [
  {
    id: 1,
    name: 'Batman',
    email: 'unknown',
    phone: 'unknown'
  },
  {
    id: 2,
    name: 'Alfred Pennyworth',
    email: 'alfred@waynemanor.com',
    phone: '9988776655'
  },
  {
    id: 3,
    name: 'Robin',
    email: 'robin@wayneinc.com',
    phone: 'unknown'
  }
  ];

var regexes = [
  {
    caption: "Please enter your mail address",
    regex: '^[a-z]+@[a-z]+.[a-z]+$'
  },
  {
    caption: "Please enter your phone number",
    regex: '^[0-9]{10}$'
  }
  ];

The plnkr link

如果你的正则表达式变量是范围变量,你可以简单地将它放入ng-pattern属性而不创建函数:
<input ng-pattern="{{testRegex}}" name="testInput3" ng-model="testVar3" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM