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?

9
  • 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" Commented Jun 1, 2018 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. Commented Jun 1, 2018 at 18:16
  • But that is all you need: build the pattern dynamically - $scope.myPattern = new RegExp("^(?!.*("+listFromServer.join('|')+"))") and use ng-pattern="myPattern". Commented Jun 1, 2018 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'] Commented Jun 1, 2018 at 18:25
  • That seems out of scope of your current question, which sounds off-topic now. Commented Jun 1, 2018 at 18:33

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.