formvalidation
Version:
The best jQuery plugin to validate form fields. Support Bootstrap, Foundation, Pure, SemanticUI, UIKit and custom frameworks
86 lines (77 loc) • 3.09 kB
JavaScript
/**
* lessThan validator
*
* @link http://formvalidation.io/validators/lessThan/
* @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': {
lessThan: {
'default': 'Please enter a value less than or equal to %s',
notInclusive: 'Please enter a value less than %s'
}
}
});
FormValidation.Validator.lessThan = {
html5Attributes: {
message: 'message',
value: 'value',
inclusive: 'inclusive'
},
enableByHtml5: function($field) {
var type = $field.attr('type'),
max = $field.attr('max');
if (max && type !== 'date') {
return {
value: max
};
}
return false;
},
/**
* Return true if the input value is less than or equal to given number
*
* @param {FormValidation.Base} validator The validator plugin instance
* @param {jQuery} $field Field element
* @param {Object} options Can consist of the following keys:
* - value: The number used to compare to. It 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, 'lessThan');
if (value === '') {
return true;
}
value = this._format(value);
if (!$.isNumeric(value)) {
return false;
}
var locale = validator.getLocale(),
compareTo = $.isNumeric(options.value) ? options.value : validator.getDynamicOption($field, options.value),
compareToValue = this._format(compareTo);
value = parseFloat(value);
return (options.inclusive === true || options.inclusive === undefined)
? {
valid: value <= compareToValue,
message: FormValidation.Helper.format(options.message || FormValidation.I18n[locale].lessThan['default'], compareTo)
}
: {
valid: value < compareToValue,
message: FormValidation.Helper.format(options.message || FormValidation.I18n[locale].lessThan.notInclusive, compareTo)
};
},
_format: function(value) {
return (value + '').replace(',', '.');
}
};
}(jQuery));