2016-11-16 60 views
0

我有正则表达式这对我的需求工作正常。现在我想限制这个正则表达式,以便它只允许0到15个字符。所以我把它改成$scope.pa = /^([\[email protected]#\$]+){0,15}$/i; 但是0到15个字符的限制没有解决。Angularjs正则表达式限制字符数问题

<!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 = /^([\[email protected]#\$]+)$/i; 

      }]); 
</script> 
</body> 
</html> 
+0

'/^[!\ W \ - 〜!@#\ $] {0,15} $/I;' – Tushar

+0

Tushar,工作正常并解决了问题 –

回答

2

现在我想限制这种正则表达式,以便它可以只允许0到15个字符。

为了实现这一点,你应该在字符类施加范围限制[]而不是组()

现在你已经将它应用到整个/^([\[email protected]#\$]+){0,15}$/i其中重复无限字符0到15次。这使得范围限制无用。

因此,{0,15}应该来[\[email protected]#\$]后,你的正则表达式将是:

/^([\w\[email protected]#\$]{0,15})$/i;