How do I restrict an input to only accept numbers?

前端 未结 17 1233
感情败类
感情败类 2020-12-07 09:28

I am using ngChange in AngularJS to trigger a custom function that will remove any letters the user adds to the input.



        
17条回答
  •  执笔经年
    2020-12-07 10:19

    I ended up creating a modified directive of the above code to accept input and change the format on the fly...

    .directive('numericOnly', function($filter) {
      return {
          require: 'ngModel',
          link: function(scope, element, attrs, modelCtrl) {
    
               element.bind('keyup', function (inputValue, e) {
                 var strinput = modelCtrl.$$rawModelValue;
                 //filter user input
                 var transformedInput = strinput ? strinput.replace(/[^,\d.-]/g,'') : null;
                 //remove trailing 0
                 if(transformedInput.charAt(0) <= '0'){
                   transformedInput = null;
                   modelCtrl.$setViewValue(transformedInput);
                   modelCtrl.$render();
                 }else{
                   var decimalSplit = transformedInput.split(".")
                   var intPart = decimalSplit[0];
                   var decPart = decimalSplit[1];
                   //remove previously formated number
                   intPart = intPart.replace(/,/g, "");
                   //split whole number into array of 3 digits
                   if(intPart.length > 3){
                     var intDiv = Math.floor(intPart.length / 3);
                     var strfraction = [];
                     var i = intDiv,
                         j = 3;
    
                     while(intDiv > 0){
                       strfraction[intDiv] = intPart.slice(intPart.length-j,intPart.length - (j - 3));
                       j=j+3;
                       intDiv--;
                     }
                     var k = j-3;
                     if((intPart.length-k) > 0){
                       strfraction[0] = intPart.slice(0,intPart.length-k);
                     }
                   }
                   //join arrays
                   if(strfraction == undefined){ return;}
                     var currencyformat = strfraction.join(',');
                     //check for leading comma
                     if(currencyformat.charAt(0)==','){
                       currencyformat = currencyformat.slice(1);
                     }
    
                     if(decPart ==  undefined){
                       modelCtrl.$setViewValue(currencyformat);
                       modelCtrl.$render();
                       return;
                     }else{
                       currencyformat = currencyformat + "." + decPart.slice(0,2);
                       modelCtrl.$setViewValue(currencyformat);
                       modelCtrl.$render();
                     }
                 }
                });
          }
      };
    

    })

提交回复
热议问题