Muralidharan R
Muralidharan R

Reputation: 23

Angular dynamic ngPattern

I'm trying to implement dynamic ngPattern.

My regex changes when the user clicks on a button or selects a value from dropdown.

But for some reason this doesnt seem to work. Below is the code.

 app.controller('testController',function(){

    $scope.pattern = new RegExp('^\w{1,10}$');

    $scope.changePattern = function () {
        $scope.pattern = new RegExp('^\d{5}$');
    };

 });

But when i try something like this, it works.

    $scope.pattern = /^\w{1,10}$/;

    $scope.changePattern = function () {
        $scope.pattern = /^\d{5}$/;
    };

I'm not sure why using new RegExp() is not working. The reason I had to use new RegExp() is that I get this in a JSON response as string.

Upvotes: 2

Views: 2292

Answers (1)

New Dev
New Dev

Reputation: 49590

This is because backlash (\) is a special character that you need to escape with "\\" when you are constructing a string:

$scope.pattern = new RegExp('^\\w{1,10}$');

So this has nothing to do with RegExp or with ng-pattern.

Upvotes: 2

Related Questions