0

I have a form that needs to validate for specific first name.

<input type="text" ng-model="info.first_name" ng-pattern="/\bJane\b/">

The issue is that the first name "Jane" needs to be set in the controller.

Is it possible to dynamically set this using ng-pattern?

plunkr

user2954587
  • 4,661
  • 6
  • 43
  • 101
  • Take a look at this http://stackoverflow.com/a/18984874/13468, there are two ways shown to do this. – mlibby Feb 20 '15 at 22:57
  • @mlibby I saw that question but I'd rather not use a directive and don't believe it's possible to create a regex with a string while not making the regex a string. I've added a plunkr – user2954587 Feb 20 '15 at 23:20

2 Answers2

0

You can see the full plunkr I made from yours, but the relevant bit is adapted from https://stackoverflow.com/a/18984874/13468

$scope.getPattern = (function() {
    var regexp = function() {return new RegExp('\\b'+ $scope.second_name +'\\b')};
    return {
      test: function (value) {
        return regexp().test(value);
      }
    }
  })();

I used a function for the internal regexp because I want to wait until the pattern is actually tested to get the value of $scope.second_name to include in the RegExp.

Community
  • 1
  • 1
mlibby
  • 6,567
  • 1
  • 32
  • 41
0

You can just define the regex as a scope variable:

 $scope.pattern = new RegExp('\\b' + $scope.second_name + '\\b');

 <input type="text" ng-model="first_name" ng-pattern="pattern" required>  

http://plnkr.co/edit/fsAILhdutlSf3ztcgZDA

cyberwombat
  • 38,105
  • 35
  • 175
  • 251