0

Is it possible to set ng-pattern to something which is return in function? My pattern is create dynamically (depends on what is click on the site), so I need something like this:

<input ng-pattern="myPattern()">
$scope.myPattern = function(){ 
   var list = listFromServer.join('|'); 
   return new RegExp("^(?!.*("+list+")).*$")
}

But it obviously doesn't work. How can I deal with it and create dynamic regex pattern if my 'listFromServer' is also dynamically and depends on user clicking?

emka26
  • 433
  • 1
  • 11
  • 28
  • Yes, it is possible. Define the pattern in the `$scope` and use a variable in the `ng-pattern`. E.g. `$scope.myPattern = /my_pattern/` and then `ng-pattern="myPattern"` – Wiktor Stribiżew Jun 01 '18 at 18:05
  • @WiktorStribiżew but /my_pattern/ is variable and change dynamically... So I can't just use $scope.myPattern = /my_pattern/, I must use it in the function because here new RegExp("^(?!.*("+list+")).*$") is a list and list is a variable and I get it dynamically. So no, you solution doesn't work for me. – emka26 Jun 01 '18 at 18:16
  • But that is all you need: build the pattern dynamically - `$scope.myPattern = new RegExp("^(?!.*("+listFromServer.join('|')+"))")` and use `ng-pattern="myPattern"`. – Wiktor Stribiżew Jun 01 '18 at 18:18
  • But what about listFromServer? I create it also dynamically! Depends which dropdown user choose, listFromServer is different, so I must observe it, and only then assign it to the list. So I must have a function which get properly data (listFromServer), depends on what user do and then create this pattern, based on this list. So imagine that when You choose "dog" on the site, your listFromServer looks like ['Johny', 'Rex'], but if you choose "cat" your listFromServer looks like ['Vicky', 'Iris'] – emka26 Jun 01 '18 at 18:25
  • That seems out of scope of your current question, which sounds off-topic now. – Wiktor Stribiżew Jun 01 '18 at 18:33
  • Maybe I'm not precise so I fixed it (but I wrote earlier that "My pattern is created dynamically (depends on what is click on the site)", so I thought that it's clear. But I corrected it, so can you answer for this question? – emka26 Jun 01 '18 at 18:40
  • I think you should remove the `ng-pattern` from html and check the pattern in the AngularJS controller in this particular case. – lealceldeiro Jun 01 '18 at 20:19
  • It would be best if you provided a plunkr or codepen with your code. – Wiktor Stribiżew Jun 01 '18 at 20:23
  • Also, see https://stackoverflow.com/questions/30458380/angularjs-dynamic-ng-pattern-not-working – Wiktor Stribiżew Jun 01 '18 at 20:42

0 Answers0