0

我创建指令用于验证NIC没有如下角JS国家身份证号验证

CustomerCompanyApp.directive('nicOnly', function() { 
    return { 
     restrict: "A", 
     require: 'ngModel', 
     link: function (scope, elem, attrs, modelCtrl) { 
      var limit = parseInt(attrs.nicOnly); 
      elem.bind('keypress', function (e) { 

       //console.log(e.charCode); 
       if (elem[0].value.length >= limit) { 
        if (e.charCode != 0) { 
         //console.log(e.charCode); 
         e.preventDefault(); 
         return false; 
        } 

       } else { 
        if (elem[0].value.length == limit - 1) { 

         modelCtrl.$parsers.push(function (inputValue) { 
          var transformedInput = inputValue ? inputValue.replace(/^[X|x|V|v]$/, '') : null; 

          if (transformedInput != inputValue) { 
           modelCtrl.$setViewValue(transformedInput); 
           modelCtrl.$render(); 
          } 

          return transformedInput; 
         }); 


        } else { 
         modelCtrl.$parsers.push(function (inputValue) { 
          var transformedInput = inputValue ? inputValue.replace(/[^\d]/g, '') : null; 

          if (transformedInput != inputValue) { 
           modelCtrl.$setViewValue(transformedInput); 
           modelCtrl.$render(); 
          } 

          return transformedInput; 
         }); 
        } 
       } 
      }); 
     } 
    }; 
}); 

在CHTML

<div class="form-group"> 
       <label class="control-label" for="customerNicNoforconfirmation">National identity card no</label> 
       <input class="form-control" type="text" name="customerNicNoforconfirmation" id="customerNicNoforconfirmation1" ng-model="customerNicNoforconfirmation" required="" nic-only="10"> 
       <p ng-show="NicDetailsform.customerNicNoforconfirmation.$invalid && !NicDetailsform.customerNicNoforconfirmation.$pristine" class="danger">Customer Nic Required.</p> 
      </div> 

在上述指令可以限制长度和输入只有数字。 但现在我想在添加此验证我的指令,

  1. 输入的第一个9个字符必须是数字。
  2. 输入的最后1个字符必须是V v X x Letter。整个输入的
  3. 长度必须是10

在我的指令,它会限制整个输入长度为10,所有的输入都只有数字。我无法找到克服其他要求的方法。

回答

0

我找不到办法解决这个使用指令 终于让我找到NG-模式来解决我的问题

<div class="form-group"> 
          <label class="control-label" for="customerNicNoforconfirmation">National identity card no</label> 
          <input class="form-control" type="text" name="customerNicNoforconfirmation" id="customerNicNoforconfirmation" ng-model="customerNicNoforconfirmation" required="" ng-pattern="/^\d{9}[V|v|X|x]$/" limit-to="10"> 
          <p ng-show="NicDetailsform.customerNicNoforconfirmation.$dirty && NicDetailsform.customerNicNoforconfirmation.$error.pattern" class="danger">First 9 characters must be numbers and last character must be V or X letter </p> 
         </div> 

NG模式=“/^\ d {9} [V | V | X | x] $ /“