step.js 2.0 KB

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