How do I restrict an input to only accept numbers?

前端 未结 17 1229
感情败类
感情败类 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:16

    you may also want to remove the 0 at the beginning of the input... I simply add an if block to Mordred answer above because I cannot make a comment yet...

      app.directive('numericOnly', function() {
        return {
          require: 'ngModel',
          link: function(scope, element, attrs, modelCtrl) {
    
              modelCtrl.$parsers.push(function (inputValue) {
                  var transformedInput = inputValue ? inputValue.replace(/[^\d.-]/g,'') : null;
    
                  if (transformedInput!=inputValue) {
                      modelCtrl.$setViewValue(transformedInput);
                      modelCtrl.$render();
                  }
                  //clear beginning 0
                  if(transformedInput == 0){
                    modelCtrl.$setViewValue(null);
                    modelCtrl.$render();
                  }
                  return transformedInput;
              });
          }
        };
      })
    

提交回复
热议问题