step.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. (function($) {
  2. $.fn.bootstrapValidator.validators.step = {
  3. /**
  4. * Return true if the input value is valid step one
  5. *
  6. * @param {BootstrapValidator} validator The validator plugin instance
  7. * @param {jQuery} $field Field element
  8. * @param {Object} options Can consist of the following keys:
  9. * - baseValue: The base value
  10. * - step: The step
  11. * - message: The invalid message
  12. * @returns {Boolean}
  13. */
  14. validate: function(validator, $field, options) {
  15. var value = $field.val();
  16. if (value == '') {
  17. return true;
  18. }
  19. options = $.extend({}, { baseValue: 0, step: 1 }, options);
  20. value = parseFloat(value);
  21. if (isNaN(value) || !isFinite(value)) {
  22. return false;
  23. }
  24. var round = function(x, precision) {
  25. var m = Math.pow(10, precision);
  26. x = x * m;
  27. var sign = (x > 0) | -(x < 0),
  28. isHalf = (x % 1 === 0.5 * sign);
  29. if (isHalf) {
  30. return (Math.floor(x) + (sign > 0)) / m;
  31. } else {
  32. return Math.round(x) / m;
  33. }
  34. },
  35. floatMod = function(x, y) {
  36. if (y == 0.0) {
  37. return 1.0;
  38. }
  39. var dotX = (x + '').split('.'),
  40. dotY = (y + '').split('.'),
  41. precision = ((dotX.length == 1) ? 0 : dotX[1].length) + ((dotY.length == 1) ? 0 : dotY[1].length);
  42. return round(x - y * Math.floor(x / y), precision);
  43. };
  44. var mod = floatMod(value - options.baseValue, options.step);
  45. return (mod == 0.0 || mod == options.step);
  46. }
  47. };
  48. }(window.jQuery));