使用破折号angularjs验证数字

时间:2014-09-08 19:30:14

标签: javascript regex angularjs

您好我有一个输入字段,我想进行验证,输入只有数字,但有破折号,最多11个数字

  i.e  1233-224-1234

我已应用以下验证仅接受数字

  <input ng-pattern="customNum" ng-model=value.id />
   In my controller I have 

function myCtrl($scope) {
    $scope.customNum = /^\d+$/;
}

请让我知道如何更新这个,以便输入13位数字,其中11位是数字,2位是破折号。 谢谢

3 个答案:

答案 0 :(得分:1)

请参见此处:http://jsbin.com/talaz/1/

<form name="form" class="css-form" novalidate>      

        <input type="text" ng-model="code" name="code" ng-pattern='/^\d{4}-\d{3}-\d{4}$/'    />Code :{{code}}<br />        
        <span ng-show="form.size.$error.pattern ">
          The code need to falow that 1234-123-1234 pattern</span>
 </form>

答案 1 :(得分:0)

如果数字未修复,您可以尝试此操作:

^\d+[-]\d+[-]\d+$

如果你的数字是固定的,那么:

^\d{4}-\d{3}-\d{4}$

答案 2 :(得分:0)

如果您想要一个可以在很多地方使用并在一个地方更改的可重用验证,您可以使用自定义验证器指令。我只是为了这个例子而称它为信用卡验证器。

<form name="form">
   <input type="text" ng-model="user.creditcard" name="creditcardNumber" validate-creditcard>
   <span ng-show="form.creditcardNumber.$error.creditcard">
      This is not a valid credit card number.
   </span>
</form>

 app.directive('validateCreditcard', function() {
      var creditcardRegex = /^\d{4}-\d{3}-\d{4}$/;

      return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, el, attr, ngModelCtrl) {
          ngModelCtrl.$parsers.unshift(function(input) {
            var valid = creditcardRegex.test(input);
            ngModelCtrl.$setValidity('creditcard', valid);
            return valid;
          }); 
        }
      };
    });

example on plnkr