Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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)

share|improve this question

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer
    
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. –  sonu703 Apr 9 at 17:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.