Float range validation using AngularJs

柔情痞子 提交于 2019-12-11 02:31:56

问题


I am following an example based on official docs to validate float. My added requirement is that float value should lie between -90 to 90. I added the min and max fields but still no luck.

Below is the code:

HTML:

<body ng-app="form-example1">
<form name="form" class="css-form" novalidate>

<div>
  Length (float):
  <input type="text" ng-model="length" name="length"  min="-90" max="90" smart-float />
  {{length}}<br />
  <span ng-show="form.length.$error.float">
    This is not a valid float number!</span>
     <span ng-show="form.length.$error.min || form.length.$error.max">
    The value must be in range -90 to 90!</span>
</div>

JS:

var app = angular.module('form-example1', []);
var FLOAT_REGEXP = /^\-?\d+((\.|\,)\d+)?$/;
app.directive('smartFloat', function() {
return {
  require: 'ngModel',
  link: function(scope, elm, attrs, ctrl) {
    ctrl.$parsers.unshift(function(viewValue) {
      if (FLOAT_REGEXP.test(viewValue)) {
        ctrl.$setValidity('float', true);
        return parseFloat(viewValue.replace(',', '.'));
      } else {
        ctrl.$setValidity('float', false);
        return undefined;
      }
    });
  }
};
});

Right now validations for min and max fields are not working. 90 is allowed but anything higher than is not allowed (like 90.12345 is not allowed, 90 is allowed, 89.9999 is allowed, -90.1 is not allowed)


回答1:


Be sure to make your input of type number! The min/max validation is only available for this type of input field. Compare the docs for number to text.




回答2:


<input type="text" name="number" smart-float>



app.directive('smartFloat', function() {
        return {
            restrict: 'A',
            require: '?ngModel',
            link: function(scope, element, attrs, modelCtrl) {
                modelCtrl.$parsers.push(function(inputValue) {
                    if (inputValue == undefined) return '';
                    var transformedInput = inputValue.replace(/[^0-9.]/g, '');
                    if (transformedInput !== inputValue) {
                        modelCtrl.$setViewValue(transformedInput);
                        modelCtrl.$render();
                    }
                    return transformedInput;
                });
            }
        };
    });


来源:https://stackoverflow.com/questions/22943807/float-range-validation-using-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!