Angular 1.0.2 integer directive

by vaiism

HTML

<div ng-app="form-example1">
  <div ng-controller="Controller">
    <form name="form" class="css-form" novalidate>
      <div>
        Size (integer 0 - 10):
        <input type="number" ng-model="size" name="size"
               min="0" max="10" integer />{{size}}<br />
        <span ng-show="form.size.$error.integer">This is not valid integer!</span>
        <span ng-show="form.size.$error.min || form.size.$error.max">
          The value must be in range 0 to 10!</span>
      </div>
  
      <div>
        Length (float):
        <input type="text" ng-model="length" name="length" smart-float />
        {{length}}<br />
        <span ng-show="form.length.$error.float">
          This is not a valid float number!</span>
      </div>
    </form>
  </div>
</div>

CSS

</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> 
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<style>
.ng-invalid { border: 1px solid red; }

JavaScript

var app = angular.module('form-example1', []);

var INTEGER_REGEXP = /^\-?\d*$/;
app.directive('integer', function() {
  return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {
      ctrl.$parsers.unshift(function(viewValue) {
        if (INTEGER_REGEXP.test(viewValue)) {
          // it is valid
          ctrl.$setValidity('integer', true);
          return viewValue;
        } else {
          // it is invalid, return undefined (no model update)
          ctrl.$setValidity('integer', false);
          return undefined;
        }
      });
    }
  };
});

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;
        }
      });
    }
  };
});