2

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)

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

making it as number still allows user to enter letters. and the directive for float receives the entered value as empty or null as this is how type number works if you enter characters. So on the front end i am unable to do validation just regular angular style. I ended up using a text type and in the did the actual range validation in the directive.
0
<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;
                });
            }
        };
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.