UNPKG

formvalidation

Version:

The best jQuery plugin to validate form fields. Support Bootstrap, Foundation, Pure, SemanticUI, UIKit and custom frameworks

78 lines (72 loc) 2.77 kB
/** * step validator * * @link http://formvalidation.io/validators/step/ * @author https://twitter.com/nghuuphuoc * @copyright (c) 2013 - 2015 Nguyen Huu Phuoc * @license http://formvalidation.io/license/ */ (function($) { FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, { 'en_US': { step: { 'default': 'Please enter a valid step of %s' } } }); FormValidation.Validator.step = { html5Attributes: { message: 'message', base: 'baseValue', step: 'step' }, /** * Return true if the input value is valid step one * * @param {FormValidation.Base} validator The validator plugin instance * @param {jQuery} $field Field element * @param {Object} options Can consist of the following keys: * - baseValue: The base value * - step: The step * - message: The invalid message * @returns {Boolean|Object} */ validate: function(validator, $field, options) { var value = validator.getFieldValue($field, 'step'); if (value === '') { return true; } options = $.extend({}, { baseValue: 0, step: 1 }, options); value = parseFloat(value); if (!$.isNumeric(value)) { return false; } var round = function(x, precision) { var m = Math.pow(10, precision); x = x * m; var sign = (x > 0) | -(x < 0), isHalf = (x % 1 === 0.5 * sign); if (isHalf) { return (Math.floor(x) + (sign > 0)) / m; } else { return Math.round(x) / m; } }, floatMod = function(x, y) { if (y === 0.0) { return 1.0; } var dotX = (x + '').split('.'), dotY = (y + '').split('.'), precision = ((dotX.length === 1) ? 0 : dotX[1].length) + ((dotY.length === 1) ? 0 : dotY[1].length); return round(x - y * Math.floor(x / y), precision); }; var locale = validator.getLocale(), mod = floatMod(value - options.baseValue, options.step); return { valid: mod === 0.0 || mod === options.step, message: FormValidation.Helper.format(options.message || FormValidation.I18n[locale].step['default'], [options.step]) }; } }; }(jQuery));