0

I have have the regular expression $scope.pa = /^([\w-~!@#\$]+)$/i which is working fine for my requirements. Now I want to restrict this regular expression so that it can allow only 0 to 15 characters. So I have changed it to $scope.pa = /^([\w-~!@#\$]+){0,15}$/i; but that 0 to 15 characters restriction is not working out.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
</head>
<body ng-app="app">
    <div ng-controller="controllerName">
        <ng-form name="mailForm">
             Pname: <input type="text" ng-model="pname" name="pname" ng-pattern="pa" /><br />
            <span ng-show="mailForm.pname.$error.pattern" style="color:red">Please enter pname</span>


        </ng-form>
    </div>
    <script>
    var app = angular.module("app", []);
    app.controller('controllerName', ['$scope', function ($scope) {
         $scope.pname = "abcd267g";
           $scope.pa = /^([\w-~!@#\$]+)$/i;

          }]);
</script>
</body>
</html>
2
  • /^[\w\-~!@#\$]{0,15}$/i; Commented Nov 16, 2016 at 6:02
  • Tushar, working fine and solved the issue Commented Nov 16, 2016 at 6:04

1 Answer 1

2

Now I want to restrict this regular expression so that it can allow only 0 to 15 characters.

To achieve this you should be applying range restriction on character class [ ] and not the group ( ).

Right now you have applied it to whole group /^([\w-~!@#\$]+){0,15}$/i which will repeat infinite characters 0 to 15 times. Which renders range restriction useless.

Thus, {0,15} should come after [\w-~!@#\$] and your regex will be:

/^([\w\-~!@#\$]{0,15})$/i;

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

Comments

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.