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] $ /「