ean.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. (function($) {
  2. $.fn.bootstrapValidator.i18n.ean = $.extend($.fn.bootstrapValidator.i18n.ean || {}, {
  3. 'default': 'Please enter a valid EAN number'
  4. });
  5. $.fn.bootstrapValidator.validators.ean = {
  6. /**
  7. * Validate EAN (International Article Number)
  8. * Examples:
  9. * - Valid: 73513537, 9780471117094, 4006381333931
  10. * - Invalid: 73513536
  11. *
  12. * @see http://en.wikipedia.org/wiki/European_Article_Number
  13. * @param {BootstrapValidator} validator The validator plugin instance
  14. * @param {jQuery} $field Field element
  15. * @param {Object} options Can consist of the following keys:
  16. * - message: The invalid message
  17. * @returns {Boolean}
  18. */
  19. validate: function(validator, $field, options) {
  20. var value = $field.val();
  21. if (value === '') {
  22. return true;
  23. }
  24. if (!/^(\d{8}|\d{12}|\d{13})$/.test(value)) {
  25. return false;
  26. }
  27. var length = value.length,
  28. sum = 0,
  29. weight = (length === 8) ? [3, 1] : [1, 3];
  30. for (var i = 0; i < length - 1; i++) {
  31. sum += parseInt(value.charAt(i), 10) * weight[i % 2];
  32. }
  33. sum = (10 - sum % 10) % 10;
  34. return (sum + '' === value.charAt(length - 1));
  35. }
  36. };
  37. }(jQuery));