step.js 2.3 KB

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