bootstrapvalidator
Version:
The best jQuery plugin to validate form fields. Designed to use with Bootstrap 3
41 lines (37 loc) • 1.42 kB
JavaScript
(function($) {
$.fn.bootstrapValidator.i18n.ean = $.extend($.fn.bootstrapValidator.i18n.ean || {}, {
'default': 'Please enter a valid EAN number'
});
$.fn.bootstrapValidator.validators.ean = {
/**
* Validate EAN (International Article Number)
* Examples:
* - Valid: 73513537, 9780471117094, 4006381333931
* - Invalid: 73513536
*
* @see http://en.wikipedia.org/wiki/European_Article_Number
* @param {BootstrapValidator} validator The validator plugin instance
* @param {jQuery} $field Field element
* @param {Object} options Can consist of the following keys:
* - message: The invalid message
* @returns {Boolean}
*/
validate: function(validator, $field, options) {
var value = $field.val();
if (value === '') {
return true;
}
if (!/^(\d{8}|\d{12}|\d{13})$/.test(value)) {
return false;
}
var length = value.length,
sum = 0,
weight = (length === 8) ? [3, 1] : [1, 3];
for (var i = 0; i < length - 1; i++) {
sum += parseInt(value.charAt(i), 10) * weight[i % 2];
}
sum = (10 - sum % 10) % 10;
return (sum + '' === value.charAt(length - 1));
}
};
}(window.jQuery));