2

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. That saved me sometime. Didnt realize it because of the escape character.

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.