step.js 2.4 KB

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