/** * ean validator * * @link http://formvalidation.io/validators/ean/ * @author https://twitter.com/nghuuphuoc * @copyright (c) 2013 - 2015 Nguyen Huu Phuoc * @license http://formvalidation.io/license/ */ (function(root, factory) { "use strict"; // AMD module is defined if (typeof define === "function" && define.amd) { define("validator/ean", ["jquery", "base"], factory); } else { // planted over the root! factory(root.jQuery, root.FormValidation); } }(this, function ($, FormValidation) { FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, { 'en_US': { ean: { 'default': 'Please enter a valid EAN number' } } }); FormValidation.Validator.ean = { /** * Validate EAN (International Article Number) * Examples: * - Valid: 73513537, 9780471117094, 4006381333931 * - Invalid: 73513536 * * @see http://en.wikipedia.org/wiki/European_Article_Number * @param {FormValidation.Base} 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 = validator.getFieldValue($field, 'ean'); 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)); } }; return FormValidation.Validator.ean; }));