UNPKG

formvalidation

Version:

The best jQuery plugin to validate form fields. Support Bootstrap, Foundation, Pure, SemanticUI, UIKit and custom frameworks

58 lines (52 loc) 1.92 kB
/** * imo validator * * @link http://formvalidation.io/validators/imo/ * @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': { imo: { 'default': 'Please enter a valid IMO number' } } }); FormValidation.Validator.imo = { /** * Validate IMO (International Maritime Organization) * Examples: * - Valid: IMO 8814275, IMO 9176187 * - Invalid: IMO 8814274 * * @see http://en.wikipedia.org/wiki/IMO_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, 'imo'); if (value === '') { return true; } if (!/^IMO \d{7}$/i.test(value)) { return false; } // Grab just the digits var sum = 0, digits = value.replace(/^.*(\d{7})$/, '$1'); // Go over each char, multiplying by the inverse of it's position // IMO 9176187 // (9 * 7) + (1 * 6) + (7 * 5) + (6 * 4) + (1 * 3) + (8 * 2) = 147 // Take the last digit of that, that's the check digit (7) for (var i = 6; i >= 1; i--) { sum += (digits.slice((6 - i), -i) * (i + 1)); } return sum % 10 === parseInt(digits.charAt(6), 10); } }; }(jQuery));