formvalidation
Version:
The best jQuery plugin to validate form fields. Support Bootstrap, Foundation, Pure, SemanticUI, UIKit and custom frameworks
91 lines (82 loc) • 3.33 kB
JavaScript
/**
* between validator
*
* @link http://formvalidation.io/validators/between/
* @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': {
between: {
'default': 'Please enter a value between %s and %s',
notInclusive: 'Please enter a value between %s and %s strictly'
}
}
});
FormValidation.Validator.between = {
html5Attributes: {
message: 'message',
min: 'min',
max: 'max',
inclusive: 'inclusive'
},
enableByHtml5: function($field) {
if ('range' === $field.attr('type')) {
return {
min: $field.attr('min'),
max: $field.attr('max')
};
}
return false;
},
/**
* Return true if the input value is between (strictly or not) two given numbers
*
* @param {FormValidation.Base} validator The validator plugin instance
* @param {jQuery} $field Field element
* @param {Object} options Can consist of the following keys:
* - min
* - max
*
* The min, max keys define the number which the field value compares to. min, max can be
* - A number
* - Name of field which its value defines the number
* - Name of callback function that returns the number
* - A callback function that returns the number
*
* - inclusive [optional]: Can be true or false. Default is true
* - message: The invalid message
* @returns {Boolean|Object}
*/
validate: function(validator, $field, options) {
var value = validator.getFieldValue($field, 'between');
if (value === '') {
return true;
}
value = this._format(value);
if (!$.isNumeric(value)) {
return false;
}
var locale = validator.getLocale(),
min = $.isNumeric(options.min) ? options.min : validator.getDynamicOption($field, options.min),
max = $.isNumeric(options.max) ? options.max : validator.getDynamicOption($field, options.max),
minValue = this._format(min),
maxValue = this._format(max);
value = parseFloat(value);
return (options.inclusive === true || options.inclusive === undefined)
? {
valid: value >= minValue && value <= maxValue,
message: FormValidation.Helper.format(options.message || FormValidation.I18n[locale].between['default'], [min, max])
}
: {
valid: value > minValue && value < maxValue,
message: FormValidation.Helper.format(options.message || FormValidation.I18n[locale].between.notInclusive, [min, max])
};
},
_format: function(value) {
return (value + '').replace(',', '.');
}
};
}(jQuery));