bootstrapValidator.js 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368
  1. /**
  2. * BootstrapValidator (http://bootstrapvalidator.com)
  3. *
  4. * The best jQuery plugin to validate form fields. Designed to use with Bootstrap 3
  5. *
  6. * @author http://twitter.com/nghuuphuoc
  7. * @copyright (c) 2013 - 2014 Nguyen Huu Phuoc
  8. * @license MIT
  9. */
  10. (function($) {
  11. var BootstrapValidator = function(form, options) {
  12. this.$form = $(form);
  13. this.options = $.extend({}, BootstrapValidator.DEFAULT_OPTIONS, options);
  14. this.$invalidFields = $([]); // Array of invalid fields
  15. this.$submitButton = null; // The submit button which is clicked to submit form
  16. // Validating status
  17. this.STATUS_NOT_VALIDATED = 'NOT_VALIDATED';
  18. this.STATUS_VALIDATING = 'VALIDATING';
  19. this.STATUS_INVALID = 'INVALID';
  20. this.STATUS_VALID = 'VALID';
  21. // Determine the event that is fired when user change the field value
  22. // Most modern browsers supports input event except IE 7, 8.
  23. // IE 9 supports input event but the event is still not fired if I press the backspace key.
  24. // Get IE version
  25. // https://gist.github.com/padolsey/527683/#comment-7595
  26. var ieVersion = (function() {
  27. var v = 3, div = document.createElement('div'), a = div.all || [];
  28. while (div.innerHTML = '<!--[if gt IE '+(++v)+']><br><![endif]-->', a[0]);
  29. return v > 4 ? v : !v;
  30. }());
  31. var el = document.createElement('div');
  32. this._changeEvent = (ieVersion === 9 || !('oninput' in el)) ? 'keyup' : 'input';
  33. // The flag to indicate that the form is ready to submit when a remote/callback validator returns
  34. this._submitIfValid = null;
  35. // Field elements
  36. this._cacheFields = {};
  37. this._init();
  38. };
  39. // The default options
  40. BootstrapValidator.DEFAULT_OPTIONS = {
  41. // The form CSS class
  42. elementClass: 'bv-form',
  43. // Default invalid message
  44. message: 'This value is not valid',
  45. // The error messages container
  46. // It can be:
  47. // * 'tooltip' if you want to use Bootstrap tooltip to show error messages
  48. // * 'popover' if you want to use Bootstrap popover to show error messages
  49. // * a CSS selector indicating the container
  50. //
  51. // In the first two cases, since the tooltip/popover should be small enough, the plugin only shows only one error message
  52. // You also can define the message container for particular field
  53. container: null,
  54. // The field will not be live validated if its length is less than this number of characters
  55. threshold: null,
  56. // Indicate fields which won't be validated
  57. // By default, the plugin will not validate the following kind of fields:
  58. // - disabled
  59. // - hidden
  60. // - invisible
  61. //
  62. // The setting consists of jQuery filters. Accept 3 formats:
  63. // - A string. Use a comma to separate filter
  64. // - An array. Each element is a filter
  65. // - An array. Each element can be a callback function
  66. // function($field, validator) {
  67. // $field is jQuery object representing the field element
  68. // validator is the BootstrapValidator instance
  69. // return true or false;
  70. // }
  71. //
  72. // The 3 following settings are equivalent:
  73. //
  74. // 1) ':disabled, :hidden, :not(:visible)'
  75. // 2) [':disabled', ':hidden', ':not(:visible)']
  76. // 3) [':disabled', ':hidden', function($field) {
  77. // return !$field.is(':visible');
  78. // }]
  79. excluded: [':disabled', ':hidden', ':not(:visible)'],
  80. // Shows ok/error/loading icons based on the field validity.
  81. // This feature requires Bootstrap v3.1.0 or later (http://getbootstrap.com/css/#forms-control-validation).
  82. // Since Bootstrap doesn't provide any methods to know its version, this option cannot be on/off automatically.
  83. // In other word, to use this feature you have to upgrade your Bootstrap to v3.1.0 or later.
  84. //
  85. // Examples:
  86. // - Use Glyphicons icons:
  87. // feedbackIcons: {
  88. // valid: 'glyphicon glyphicon-ok',
  89. // invalid: 'glyphicon glyphicon-remove',
  90. // validating: 'glyphicon glyphicon-refresh'
  91. // }
  92. // - Use FontAwesome icons:
  93. // feedbackIcons: {
  94. // valid: 'fa fa-check',
  95. // invalid: 'fa fa-times',
  96. // validating: 'fa fa-refresh'
  97. // }
  98. feedbackIcons: {
  99. valid: null,
  100. invalid: null,
  101. validating: null
  102. },
  103. // The submit buttons selector
  104. // These buttons will be disabled to prevent the valid form from multiple submissions
  105. submitButtons: '[type="submit"]',
  106. // The custom submit handler
  107. // It will prevent the form from the default submission
  108. //
  109. // submitHandler: function(validator, form) {
  110. // - validator is the BootstrapValidator instance
  111. // - form is the jQuery object present the current form
  112. // }
  113. submitHandler: null,
  114. // Live validating option
  115. // Can be one of 3 values:
  116. // - enabled: The plugin validates fields as soon as they are changed
  117. // - disabled: Disable the live validating. The error messages are only shown after the form is submitted
  118. // - submitted: The live validating is enabled after the form is submitted
  119. live: 'enabled',
  120. // Map the field name with validator rules
  121. fields: {}
  122. };
  123. BootstrapValidator.prototype = {
  124. constructor: BootstrapValidator,
  125. /**
  126. * Init form
  127. */
  128. _init: function() {
  129. var that = this,
  130. options = {
  131. excluded: this.$form.attr('data-bv-excluded'),
  132. trigger: this.$form.attr('data-bv-trigger'),
  133. message: this.$form.attr('data-bv-message'),
  134. container: this.$form.attr('data-bv-container'),
  135. submitButtons: this.$form.attr('data-bv-submitbuttons'),
  136. threshold: this.$form.attr('data-bv-threshold'),
  137. live: this.$form.attr('data-bv-live'),
  138. fields: {},
  139. feedbackIcons: {
  140. valid: this.$form.attr('data-bv-feedbackicons-valid'),
  141. invalid: this.$form.attr('data-bv-feedbackicons-invalid'),
  142. validating: this.$form.attr('data-bv-feedbackicons-validating')
  143. }
  144. };
  145. this.$form
  146. // Disable client side validation in HTML 5
  147. .attr('novalidate', 'novalidate')
  148. .addClass(this.options.elementClass)
  149. // Disable the default submission first
  150. .on('submit.bv', function(e) {
  151. e.preventDefault();
  152. that.validate();
  153. })
  154. .on('click.bv', this.options.submitButtons, function() {
  155. that.$submitButton = $(this);
  156. // The user just click the submit button
  157. that._submitIfValid = true;
  158. })
  159. // Find all fields which have either "name" or "data-bv-field" attribute
  160. .find('[name], [data-bv-field]')
  161. .each(function() {
  162. var $field = $(this);
  163. if (that._isExcluded($field)) {
  164. return;
  165. }
  166. var field = $field.attr('name') || $field.attr('data-bv-field'),
  167. opts = that._parseOptions($field);
  168. if (opts) {
  169. $field.attr('data-bv-field', field);
  170. options.fields[field] = $.extend({}, opts, options.fields[field]);
  171. }
  172. });
  173. this.options = $.extend(true, this.options, options);
  174. for (var field in this.options.fields) {
  175. this._initField(field);
  176. }
  177. this.$form.trigger($.Event('init.form.bv'), {
  178. options: this.options
  179. });
  180. },
  181. /**
  182. * Parse the validator options from HTML attributes
  183. *
  184. * @param {jQuery} $field The field element
  185. * @returns {Object}
  186. */
  187. _parseOptions: function($field) {
  188. var field = $field.attr('name') || $field.attr('data-bv-field'),
  189. validators = {},
  190. validator,
  191. v, // Validator name
  192. enabled,
  193. optionName,
  194. optionValue,
  195. html5AttrName,
  196. html5AttrMap;
  197. for (v in $.fn.bootstrapValidator.validators) {
  198. validator = $.fn.bootstrapValidator.validators[v];
  199. enabled = $field.attr('data-bv-' + v.toLowerCase()) + '';
  200. html5AttrMap = ('function' == typeof validator.enableByHtml5) ? validator.enableByHtml5($field) : null;
  201. if ((html5AttrMap && enabled != 'false')
  202. || (html5AttrMap !== true && ('' == enabled || 'true' == enabled)))
  203. {
  204. // Try to parse the options via attributes
  205. validator.html5Attributes = validator.html5Attributes || { message: 'message' };
  206. validators[v] = $.extend({}, html5AttrMap == true ? {} : html5AttrMap, validators[v]);
  207. for (html5AttrName in validator.html5Attributes) {
  208. optionName = validator.html5Attributes[html5AttrName];
  209. optionValue = $field.attr('data-bv-' + v.toLowerCase() + '-' + html5AttrName);
  210. if (optionValue) {
  211. if ('true' == optionValue) {
  212. optionValue = true;
  213. } else if ('false' == optionValue) {
  214. optionValue = false;
  215. }
  216. validators[v][optionName] = optionValue;
  217. }
  218. }
  219. }
  220. }
  221. var opts = {
  222. feedbackIcons: $field.attr('data-bv-feedbackicons'),
  223. trigger: $field.attr('data-bv-trigger'),
  224. message: $field.attr('data-bv-message'),
  225. container: $field.attr('data-bv-container'),
  226. selector: $field.attr('data-bv-selector'),
  227. threshold: $field.attr('data-bv-threshold'),
  228. validators: validators
  229. },
  230. emptyOptions = $.isEmptyObject(opts), // Check if the field options are set using HTML attributes
  231. emptyValidators = $.isEmptyObject(validators); // Check if the field validators are set using HTML attributes
  232. if (!emptyValidators || (!emptyOptions && this.options.fields[field])) {
  233. opts.validators = validators;
  234. return opts;
  235. } else {
  236. return null;
  237. }
  238. },
  239. /**
  240. * Init field
  241. *
  242. * @param {String} field The field name
  243. */
  244. _initField: function(field) {
  245. if (this.options.fields[field] == null || this.options.fields[field].validators == null) {
  246. return;
  247. }
  248. var fields = this.getFieldElements(field);
  249. // We don't need to validate non-existing fields
  250. if (fields == []) {
  251. delete this.options.fields[field];
  252. return;
  253. }
  254. for (var validatorName in this.options.fields[field].validators) {
  255. if (!$.fn.bootstrapValidator.validators[validatorName]) {
  256. delete this.options.fields[field].validators[validatorName];
  257. }
  258. }
  259. if (this.options.fields[field]['enabled'] == null) {
  260. this.options.fields[field]['enabled'] = true;
  261. }
  262. fields.attr('data-bv-field', field);
  263. for (var i = 0; i < fields.length; i++) {
  264. this._initFieldElement($(fields[i]));
  265. }
  266. },
  267. /**
  268. * Init field element
  269. *
  270. * @param {jQuery} $field The field element
  271. */
  272. _initFieldElement: function($field) {
  273. var that = this,
  274. field = $field.attr('data-bv-field'),
  275. fields = this.getFieldElements(field),
  276. index = fields.index($field),
  277. type = $field.attr('type'),
  278. total = fields.length,
  279. updateAll = (total == 1) || ('radio' == type) || ('checkbox' == type),
  280. $parent = $field.parents('.form-group'),
  281. // Allow user to indicate where the error messages are shown
  282. container = this.options.fields[field].container || this.options.container,
  283. $message = (container && container != 'tooltip' && container != 'popover') ? $(container) : this._getMessageContainer($field);
  284. if (container && container != 'tooltip' && container != 'popover') {
  285. $message.addClass('has-error');
  286. }
  287. // Remove all error messages and feedback icons
  288. $message.find('.help-block[data-bv-validator][data-bv-for="' + field + '"]').remove();
  289. $parent.find('i[data-bv-icon-for="' + field + '"]').remove();
  290. // Whenever the user change the field value, mark it as not validated yet
  291. var event = ('radio' == type || 'checkbox' == type || 'file' == type || 'SELECT' == $field.get(0).tagName) ? 'change' : this._changeEvent;
  292. $field.off(event + '.update.bv').on(event + '.update.bv', function() {
  293. // Reset the flag
  294. that._submitIfValid = false;
  295. that.updateElementStatus($(this), that.STATUS_NOT_VALIDATED);
  296. });
  297. // Create help block elements for showing the error messages
  298. $field.data('bv.messages', $message);
  299. for (var validatorName in this.options.fields[field].validators) {
  300. $field.data('bv.result.' + validatorName, this.STATUS_NOT_VALIDATED);
  301. if (!updateAll || index == total - 1) {
  302. $('<small/>')
  303. .css('display', 'none')
  304. .addClass('help-block')
  305. .attr('data-bv-validator', validatorName)
  306. .attr('data-bv-for', field)
  307. .html(this.options.fields[field].validators[validatorName].message || this.options.fields[field].message || this.options.message)
  308. .appendTo($message);
  309. }
  310. }
  311. // Prepare the feedback icons
  312. // Available from Bootstrap 3.1 (http://getbootstrap.com/css/#forms-control-validation)
  313. if (this.options.fields[field].feedbackIcons !== false && this.options.fields[field].feedbackIcons !== 'false'
  314. && this.options.feedbackIcons
  315. && this.options.feedbackIcons.validating && this.options.feedbackIcons.invalid && this.options.feedbackIcons.valid
  316. && (!updateAll || index == total - 1))
  317. {
  318. $parent.removeClass('has-success').removeClass('has-error').addClass('has-feedback');
  319. var $icon = $('<i/>').css('display', 'none').addClass('form-control-feedback').attr('data-bv-icon-for', field).insertAfter($field);
  320. // The feedback icon does not render correctly if there is no label
  321. // https://github.com/twbs/bootstrap/issues/12873
  322. if ($parent.find('label').length == 0) {
  323. $icon.css('top', 0);
  324. }
  325. // Fix feedback icons in input-group
  326. if ($parent.find('.input-group-addon').length != 0) {
  327. $icon.css({
  328. 'top': 0,
  329. 'z-index': 100
  330. });
  331. }
  332. }
  333. // Set live mode
  334. var trigger = this.options.fields[field].trigger || this.options.trigger || event,
  335. events = $.map(trigger.split(' '), function(item) {
  336. return item + '.live.bv';
  337. }).join(' ');
  338. switch (this.options.live) {
  339. case 'submitted':
  340. break;
  341. case 'disabled':
  342. $field.off(events);
  343. break;
  344. case 'enabled':
  345. default:
  346. $field.off(events).on(events, function() {
  347. if (that._exceedThreshold($(this))) {
  348. that.validateFieldElement($(this));
  349. }
  350. });
  351. break;
  352. }
  353. },
  354. /**
  355. * Get the element to place the error messages
  356. *
  357. * @param {jQuery} $field The field element
  358. * @returns {jQuery}
  359. */
  360. _getMessageContainer: function($field) {
  361. var $parent = $field.parent();
  362. if ($parent.hasClass('form-group')) {
  363. return $parent;
  364. }
  365. var cssClasses = $parent.attr('class');
  366. if (!cssClasses) {
  367. return this._getMessageContainer($parent);
  368. }
  369. cssClasses = cssClasses.split(' ');
  370. var n = cssClasses.length;
  371. for (var i = 0; i < n; i++) {
  372. if (/^col-(xs|sm|md|lg)-\d+$/.test(cssClasses[i]) || /^col-(xs|sm|md|lg)-offset-\d+$/.test(cssClasses[i])) {
  373. return $parent;
  374. }
  375. }
  376. return this._getMessageContainer($parent);
  377. },
  378. /**
  379. * Called when all validations are completed
  380. */
  381. _submit: function() {
  382. var isValid = this.isValid(),
  383. eventType = isValid ? 'success.form.bv' : 'error.form.bv',
  384. e = $.Event(eventType);
  385. this.$form.trigger(e);
  386. // Call default handler
  387. // Check if whether the submit button is clicked
  388. if (this.$submitButton) {
  389. isValid ? this._onSuccess(e) : this._onError(e);
  390. }
  391. },
  392. /**
  393. * Check if the field is excluded.
  394. * Returning true means that the field will not be validated
  395. *
  396. * @param {jQuery} $field The field element
  397. * @returns {Boolean}
  398. */
  399. _isExcluded: function($field) {
  400. if (this.options.excluded) {
  401. // Convert to array first
  402. if ('string' == typeof this.options.excluded) {
  403. this.options.excluded = $.map(this.options.excluded.split(','), function(item) {
  404. // Trim the spaces
  405. return $.trim(item);
  406. });
  407. }
  408. var length = this.options.excluded.length;
  409. for (var i = 0; i < length; i++) {
  410. if (('string' == typeof this.options.excluded[i] && $field.is(this.options.excluded[i]))
  411. || ('function' == typeof this.options.excluded[i] && this.options.excluded[i].call(this, $field, this) == true))
  412. {
  413. return true;
  414. }
  415. }
  416. }
  417. return false;
  418. },
  419. /**
  420. * Check if the number of characters of field value exceed the threshold or not
  421. *
  422. * @param {jQuery} $field The field element
  423. * @returns {Boolean}
  424. */
  425. _exceedThreshold: function($field) {
  426. var field = $field.attr('data-bv-field'),
  427. threshold = this.options.fields[field].threshold || this.options.threshold;
  428. if (!threshold) {
  429. return true;
  430. }
  431. var type = $field.attr('type'),
  432. cannotType = ['button', 'checkbox', 'file', 'hidden', 'image', 'radio', 'reset', 'submit'].indexOf(type) != -1;
  433. return (cannotType || $field.val().length >= threshold);
  434. },
  435. // --- Events ---
  436. /**
  437. * The default handler of error.form.bv event.
  438. * It will be called when there is a invalid field
  439. *
  440. * @param {jQuery.Event} e The jQuery event object
  441. */
  442. _onError: function(e) {
  443. if (e.isDefaultPrevented()) {
  444. return;
  445. }
  446. if ('submitted' == this.options.live) {
  447. // Enable live mode
  448. this.options.live = 'enabled';
  449. var that = this;
  450. for (var field in this.options.fields) {
  451. (function(f) {
  452. var fields = that.getFieldElements(f);
  453. if (fields.length) {
  454. var type = $(fields[0]).attr('type'),
  455. event = ('radio' == type || 'checkbox' == type || 'file' == type || 'SELECT' == $(fields[0]).get(0).tagName) ? 'change' : that._changeEvent,
  456. trigger = that.options.fields[field].trigger || that.options.trigger || event,
  457. events = $.map(trigger.split(' '), function(item) {
  458. return item + '.live.bv';
  459. }).join(' ');
  460. for (var i = 0; i < fields.length; i++) {
  461. $(fields[i]).off(events).on(events, function() {
  462. if (that._exceedThreshold($(this))) {
  463. that.validateFieldElement($(this));
  464. }
  465. });
  466. }
  467. }
  468. })(field);
  469. }
  470. }
  471. // Focus to the first invalid field
  472. this.$invalidFields.eq(0).focus();
  473. },
  474. /**
  475. * The default handler of success.form.bv event.
  476. * It will be called when all the fields are valid
  477. *
  478. * @param {jQuery.Event} e The jQuery event object
  479. */
  480. _onSuccess: function(e) {
  481. if (e.isDefaultPrevented()) {
  482. return;
  483. }
  484. // Call the custom submission if enabled
  485. if (this.options.submitHandler && 'function' == typeof this.options.submitHandler) {
  486. // If you want to submit the form inside your submit handler, please call defaultSubmit() method
  487. this.options.submitHandler.call(this, this, this.$form, this.$submitButton);
  488. } else {
  489. this.disableSubmitButtons(true).defaultSubmit();
  490. }
  491. },
  492. /**
  493. * Called after validating a field element
  494. *
  495. * @param {jQuery} $field The field element
  496. */
  497. _onValidateFieldCompleted: function($field) {
  498. var field = $field.attr('data-bv-field'),
  499. validators = this.options.fields[field].validators,
  500. counter = {},
  501. numValidators = 0;
  502. counter[this.STATUS_NOT_VALIDATED] = 0;
  503. counter[this.STATUS_VALIDATING] = 0;
  504. counter[this.STATUS_INVALID] = 0;
  505. counter[this.STATUS_VALID] = 0;
  506. for (var validatorName in validators) {
  507. numValidators++;
  508. var result = $field.data('bv.result.' + validatorName);
  509. if (result) {
  510. counter[result]++;
  511. }
  512. }
  513. var index = this.$invalidFields.index($field);
  514. if (counter[this.STATUS_VALID] == numValidators) {
  515. // Remove from the list of invalid fields
  516. if (index != -1) {
  517. this.$invalidFields.splice(index, 1);
  518. }
  519. this.$form.trigger($.Event('success.field.bv'), {
  520. field: field,
  521. element: $field
  522. });
  523. }
  524. // If all validators are completed and there is at least one validator which doesn't pass
  525. else if (counter[this.STATUS_NOT_VALIDATED] == 0 && counter[this.STATUS_VALIDATING] == 0 && counter[this.STATUS_INVALID] > 0) {
  526. // Add to the list of invalid fields
  527. if (index == -1) {
  528. this.$invalidFields = this.$invalidFields.add($field);
  529. }
  530. this.$form.trigger($.Event('error.field.bv'), {
  531. field: field,
  532. element: $field
  533. });
  534. }
  535. },
  536. // --- Public methods ---
  537. /**
  538. * Retrieve the field elements by given name
  539. *
  540. * @param {String} field The field name
  541. * @returns {null|jQuery[]}
  542. */
  543. getFieldElements: function(field) {
  544. if (!this._cacheFields[field]) {
  545. this._cacheFields[field] = (this.options.fields[field] && this.options.fields[field].selector)
  546. ? $(this.options.fields[field].selector)
  547. : this.$form.find('[name="' + field + '"]');
  548. }
  549. return this._cacheFields[field];
  550. },
  551. /**
  552. * Disable/enable submit buttons
  553. *
  554. * @param {Boolean} disabled Can be true or false
  555. * @returns {BootstrapValidator}
  556. */
  557. disableSubmitButtons: function(disabled) {
  558. if (!disabled) {
  559. this.$form.find(this.options.submitButtons).removeAttr('disabled');
  560. } else if (this.options.live != 'disabled') {
  561. // Don't disable if the live validating mode is disabled
  562. this.$form.find(this.options.submitButtons).attr('disabled', 'disabled');
  563. }
  564. return this;
  565. },
  566. /**
  567. * Validate the form
  568. *
  569. * @returns {BootstrapValidator}
  570. */
  571. validate: function() {
  572. if (!this.options.fields) {
  573. return this;
  574. }
  575. this.disableSubmitButtons(true);
  576. for (var field in this.options.fields) {
  577. this.validateField(field);
  578. }
  579. this._submit();
  580. return this;
  581. },
  582. /**
  583. * Validate given field
  584. *
  585. * @param {String} field The field name
  586. * @returns {BootstrapValidator}
  587. */
  588. validateField: function(field) {
  589. var fields = this.getFieldElements(field),
  590. type = fields.attr('type'),
  591. n = (('radio' == type) || ('checkbox' == type)) ? 1 : fields.length;
  592. for (var i = 0; i < n; i++) {
  593. this.validateFieldElement($(fields[i]));
  594. }
  595. return this;
  596. },
  597. /**
  598. * Validate field element
  599. *
  600. * @param {jQuery} $field The field element
  601. * @returns {BootstrapValidator}
  602. */
  603. validateFieldElement: function($field) {
  604. var that = this,
  605. field = $field.attr('data-bv-field'),
  606. fields = this.getFieldElements(field),
  607. type = $field.attr('type'),
  608. updateAll = (fields && fields.length == 1) || ('radio' == type) || ('checkbox' == type),
  609. validators = this.options.fields[field].validators,
  610. validatorName,
  611. validateResult;
  612. if (this.options.fields[field]['enabled'] == false || this._isExcluded($field)) {
  613. return this;
  614. }
  615. for (validatorName in validators) {
  616. if ($field.data('bv.dfs.' + validatorName)) {
  617. $field.data('bv.dfs.' + validatorName).reject();
  618. }
  619. // Don't validate field if it is already done
  620. var result = $field.data('bv.result.' + validatorName);
  621. if (result == this.STATUS_VALID || result == this.STATUS_INVALID) {
  622. this._onValidateFieldCompleted($field);
  623. continue;
  624. }
  625. $field.data('bv.result.' + validatorName, this.STATUS_VALIDATING);
  626. validateResult = $.fn.bootstrapValidator.validators[validatorName].validate(this, $field, validators[validatorName]);
  627. // validateResult can be a $.Deferred object ...
  628. if ('object' == typeof validateResult) {
  629. updateAll ? this.updateStatus(field, this.STATUS_VALIDATING, validatorName)
  630. : this.updateElementStatus($field, this.STATUS_VALIDATING, validatorName);
  631. $field.data('bv.dfs.' + validatorName, validateResult);
  632. validateResult.done(function($f, v, isValid, message) {
  633. // v is validator name
  634. $f.removeData('bv.dfs.' + v);
  635. if (message) {
  636. // Update the error message
  637. $field.data('bv.messages').find('.help-block[data-bv-validator="' + v + '"][data-bv-for="' + $f.attr('data-bv-field') + '"]').html(message);
  638. }
  639. updateAll ? that.updateStatus($f.attr('data-bv-field'), isValid ? that.STATUS_VALID : that.STATUS_INVALID, v)
  640. : that.updateElementStatus($f, isValid ? that.STATUS_VALID : that.STATUS_INVALID, v);
  641. if (isValid && that._submitIfValid == true) {
  642. // If a remote validator returns true and the form is ready to submit, then do it
  643. that._submit();
  644. }
  645. });
  646. }
  647. // ... or a boolean value
  648. else if ('boolean' == typeof validateResult) {
  649. updateAll ? this.updateStatus(field, validateResult ? this.STATUS_VALID : this.STATUS_INVALID, validatorName)
  650. : this.updateElementStatus($field, validateResult ? this.STATUS_VALID : this.STATUS_INVALID, validatorName);
  651. }
  652. }
  653. return this;
  654. },
  655. /**
  656. * Update all validating results of elements which have the same field name
  657. *
  658. * @param {String} field The field name
  659. * @param {String} status The status. Can be 'NOT_VALIDATED', 'VALIDATING', 'INVALID' or 'VALID'
  660. * @param {String} [validatorName] The validator name. If null, the method updates validity result for all validators
  661. * @returns {BootstrapValidator}
  662. */
  663. updateStatus: function(field, status, validatorName) {
  664. var fields = this.getFieldElements(field),
  665. type = fields.attr('type'),
  666. n = (('radio' == type) || ('checkbox' == type)) ? 1 : fields.length;
  667. for (var i = 0; i < n; i++) {
  668. this.updateElementStatus($(fields[i]), status, validatorName);
  669. }
  670. return this;
  671. },
  672. /**
  673. * Update validating result of given element
  674. *
  675. * @param {jQuery} $field The field element
  676. * @param {String} status The status. Can be 'NOT_VALIDATED', 'VALIDATING', 'INVALID' or 'VALID'
  677. * @param {String} [validatorName] The validator name. If null, the method updates validity result for all validators
  678. * @returns {BootstrapValidator}
  679. */
  680. updateElementStatus: function($field, status, validatorName) {
  681. var that = this,
  682. field = $field.attr('data-bv-field'),
  683. $parent = $field.parents('.form-group'),
  684. $message = $field.data('bv.messages'),
  685. $allErrors = $message.find('.help-block[data-bv-validator][data-bv-for="' + field + '"]'),
  686. $errors = validatorName ? $allErrors.filter('[data-bv-validator="' + validatorName + '"]') : $allErrors,
  687. $icon = $parent.find('.form-control-feedback[data-bv-icon-for="' + field + '"]'),
  688. container = this.options.fields[field].container || this.options.container,
  689. isValidField = null;
  690. // Update status
  691. if (validatorName) {
  692. $field.data('bv.result.' + validatorName, status);
  693. } else {
  694. for (var v in this.options.fields[field].validators) {
  695. $field.data('bv.result.' + v, status);
  696. }
  697. }
  698. // Show/hide error elements and feedback icons
  699. $errors.attr('data-bv-result', status);
  700. switch (status) {
  701. case this.STATUS_VALIDATING:
  702. isValidField = null;
  703. this.disableSubmitButtons(true);
  704. $parent.removeClass('has-success').removeClass('has-error');
  705. if ($icon) {
  706. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).addClass(this.options.feedbackIcons.validating).show();
  707. }
  708. break;
  709. case this.STATUS_INVALID:
  710. isValidField = false;
  711. this.disableSubmitButtons(true);
  712. $parent.removeClass('has-success').addClass('has-error');
  713. if ($icon) {
  714. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.validating).addClass(this.options.feedbackIcons.invalid).show();
  715. }
  716. break;
  717. case this.STATUS_VALID:
  718. // If the field is valid (passes all validators)
  719. isValidField = $allErrors.filter(function() {
  720. var v = $(this).attr('data-bv-validator');
  721. return $field.data('bv.result.' + v) != that.STATUS_VALID;
  722. }).length == 0;
  723. this.disableSubmitButtons(this.$submitButton ? !this.isValid() : !isValidField);
  724. if ($icon) {
  725. $icon
  726. .removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).removeClass(this.options.feedbackIcons.valid)
  727. .addClass(isValidField ? this.options.feedbackIcons.valid : this.options.feedbackIcons.invalid)
  728. .show();
  729. }
  730. $parent.removeClass('has-error has-success').addClass(this.isValidContainer($parent) ? 'has-success' : 'has-error');
  731. break;
  732. case this.STATUS_NOT_VALIDATED:
  733. default:
  734. isValidField = null;
  735. this.disableSubmitButtons(false);
  736. $parent.removeClass('has-success').removeClass('has-error');
  737. if ($icon) {
  738. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).hide();
  739. }
  740. break;
  741. }
  742. switch (true) {
  743. // Only show the first error message if it is placed inside a tooltip ...
  744. case ($icon && 'tooltip' == container):
  745. (isValidField === false)
  746. ? $icon.css('cursor', 'pointer').tooltip('destroy').tooltip({
  747. html: true,
  748. placement: 'top',
  749. title: $allErrors.filter('[data-bv-result="' + that.STATUS_INVALID + '"]').eq(0).html()
  750. })
  751. : $icon.css('cursor', '').tooltip('destroy');
  752. break;
  753. // ... or popover
  754. case ($icon && 'popover' == container):
  755. (isValidField === false)
  756. ? $icon.css('cursor', 'pointer').popover('destroy').popover({
  757. content: $allErrors.filter('[data-bv-result="' + that.STATUS_INVALID + '"]').eq(0).html(),
  758. html: true,
  759. placement: 'top',
  760. trigger: 'hover click'
  761. })
  762. : $icon.css('cursor', '').popover('destroy');
  763. break;
  764. default:
  765. (status == this.STATUS_INVALID) ? $errors.show() : $errors.hide();
  766. break;
  767. }
  768. // Trigger an event
  769. this.$form.trigger($.Event('status.field.bv'), {
  770. field: field,
  771. element: $field,
  772. status: status
  773. });
  774. this._onValidateFieldCompleted($field);
  775. return this;
  776. },
  777. /**
  778. * Check the form validity
  779. *
  780. * @returns {Boolean}
  781. */
  782. isValid: function() {
  783. var fields, field, $field,
  784. type, status, validatorName,
  785. n, i;
  786. for (field in this.options.fields) {
  787. if (this.options.fields[field] == null || this.options.fields[field]['enabled'] == false) {
  788. continue;
  789. }
  790. fields = this.getFieldElements(field);
  791. type = fields.attr('type');
  792. n = (('radio' == type) || ('checkbox' == type)) ? 1 : fields.length;
  793. for (i = 0; i < n; i++) {
  794. $field = $(fields[i]);
  795. if (this._isExcluded($field)) {
  796. continue;
  797. }
  798. for (validatorName in this.options.fields[field].validators) {
  799. status = $field.data('bv.result.' + validatorName);
  800. if (status != this.STATUS_VALID) {
  801. return false;
  802. }
  803. }
  804. }
  805. }
  806. return true;
  807. },
  808. /**
  809. * Check if all fields inside a given container are valid.
  810. * It's useful when working with a wizard-like such as tab, collapse
  811. *
  812. * @param {jQuery} $container The container element
  813. * @returns {Boolean}
  814. */
  815. isValidContainer: function($container) {
  816. var that = this, map = {};
  817. $container.find('[data-bv-field]').each(function() {
  818. var field = $(this).attr('data-bv-field');
  819. if (!map[field]) {
  820. map[field] = $(this);
  821. }
  822. });
  823. for (var field in map) {
  824. var $f = map[field];
  825. if ($f.data('bv.messages')
  826. .find('.help-block[data-bv-validator][data-bv-for="' + field + '"]')
  827. .filter(function() {
  828. var v = $(this).attr('data-bv-validator');
  829. return ($f.data('bv.result.' + v) && $f.data('bv.result.' + v) != that.STATUS_VALID);
  830. })
  831. .length != 0)
  832. {
  833. // The field is not valid
  834. return false;
  835. }
  836. }
  837. return true;
  838. },
  839. /**
  840. * Submit the form using default submission.
  841. * It also does not perform any validations when submitting the form
  842. *
  843. * It might be used when you want to submit the form right inside the submitHandler()
  844. */
  845. defaultSubmit: function() {
  846. if (this.$submitButton) {
  847. // Create hidden input to send the submit buttons
  848. $('<input/>')
  849. .attr('type', 'hidden')
  850. .attr('data-bv-submit-hidden', '')
  851. .attr('name', this.$submitButton.attr('name'))
  852. .val(this.$submitButton.val())
  853. .appendTo(this.$form);
  854. }
  855. // Submit form
  856. this.$form.off('submit.bv').submit();
  857. },
  858. // Useful APIs which aren't used internally
  859. /**
  860. * Get the list of invalid fields
  861. *
  862. * @returns {jQuery[]}
  863. */
  864. getInvalidFields: function() {
  865. return this.$invalidFields;
  866. },
  867. /**
  868. * Get the error messages
  869. *
  870. * @param {jQuery|String} [field] The field, which can be
  871. * - a string: The field name
  872. * - a jQuery object representing the field element
  873. * If the field is not defined, the method returns all error messages of all fields
  874. * @returns {String[]}
  875. */
  876. getErrors: function(field) {
  877. var that = this,
  878. messages = [],
  879. $fields = $([]);
  880. switch (true) {
  881. case (field && 'object' == typeof field):
  882. $fields = field;
  883. break;
  884. case (field && 'string' == typeof field):
  885. var f = this.getFieldElements(field);
  886. if (f.length > 0) {
  887. var type = f.attr('type');
  888. $fields = ('radio' == type || 'checkbox' == type) ? $(f[0]) : f;
  889. }
  890. break;
  891. default:
  892. $fields = this.$invalidFields;
  893. break;
  894. }
  895. $fields.each(function() {
  896. messages = messages.concat(
  897. $(this)
  898. .data('bv.messages')
  899. .find('.help-block[data-bv-for="' + $(this).attr('data-bv-field') + '"][data-bv-result="' + that.STATUS_INVALID + '"]')
  900. .map(function() {
  901. return $(this).html()
  902. })
  903. .get()
  904. );
  905. });
  906. return messages;
  907. },
  908. /**
  909. * Add a new field
  910. *
  911. * @param {String} field The field name
  912. * @param {Object} [options] The validator rules
  913. * @returns {BootstrapValidator}
  914. */
  915. addField: function(field, options) {
  916. this.options.fields[field] = options;
  917. var fields = this.getFieldElements(field),
  918. type = fields.attr('type'),
  919. n = (('radio' == type) || ('checkbox' == type)) ? 1 : fields.length;
  920. fields.attr('data-bv-field', field);
  921. for (var i = 0; i < n; i++) {
  922. this.addFieldElement($(fields[i]), options);
  923. }
  924. this.disableSubmitButtons(false);
  925. return this;
  926. },
  927. /**
  928. * Remove a given field
  929. *
  930. * @param {String} field The field name
  931. * @returns {BootstrapValidator}
  932. */
  933. removeField: function(field) {
  934. var fields = this.getFieldElements(field),
  935. type = fields.attr('type'),
  936. n = (('radio' == type) || ('checkbox' == type)) ? 1 : fields.length;
  937. for (var i = 0; i < n; i++) {
  938. this.removeFieldElement($(fields[i]));
  939. }
  940. this.disableSubmitButtons(false);
  941. return this;
  942. },
  943. /**
  944. * Add new field element
  945. *
  946. * @param {jQuery} $field The field element
  947. * @param {Object} [options] The field options
  948. * @returns {BootstrapValidator}
  949. */
  950. addFieldElement: function($field, options) {
  951. var field = $field.attr('data-bv-field') || $field.attr('name'),
  952. type = $field.attr('type');
  953. $field.attr('data-bv-field', field);
  954. // Try to parse the options from HTML attributes
  955. var opts = this._parseOptions($field);
  956. opts = (opts == null) ? options : $.extend(true, options, opts);
  957. this.options.fields[field] = $.extend(true, this.options.fields[field], opts);
  958. // Init the element
  959. delete this._cacheFields[field];
  960. ('checkbox' == type || 'radio' == type) ? this._initField(field) : this._initFieldElement($field);
  961. this.disableSubmitButtons(false);
  962. // Trigger an event
  963. this.$form.trigger($.Event('added.field.bv'), {
  964. field: field,
  965. element: $field,
  966. options: this.options.fields[field]
  967. });
  968. return this;
  969. },
  970. /**
  971. * Remove given field element
  972. *
  973. * @param {jQuery} $field The field element
  974. * @returns {BootstrapValidator}
  975. */
  976. removeFieldElement: function($field) {
  977. var field = $field.attr('data-bv-field') || $field.attr('name'),
  978. type = $field.attr('type');
  979. $field.attr('data-bv-field', field);
  980. // Remove from the list of invalid fields
  981. var index = this.$invalidFields.index($field);
  982. if (index != -1) {
  983. this.$invalidFields.splice(index, 1);
  984. }
  985. // Update the cache
  986. delete this._cacheFields[field];
  987. if ('checkbox' == type || 'radio' == type) {
  988. this._initField(field);
  989. }
  990. this.disableSubmitButtons(false);
  991. // Trigger an event
  992. this.$form.trigger($.Event('removed.field.bv'), {
  993. field: field,
  994. element: $field
  995. });
  996. return this;
  997. },
  998. /**
  999. * Reset the form
  1000. *
  1001. * @param {Boolean} [resetFormData] Reset current form data
  1002. * @returns {BootstrapValidator}
  1003. */
  1004. resetForm: function(resetFormData) {
  1005. var field, fields, total, type, validator;
  1006. for (field in this.options.fields) {
  1007. fields = this.getFieldElements(field);
  1008. total = fields.length;
  1009. for (var i = 0; i < total; i++) {
  1010. for (validator in this.options.fields[field].validators) {
  1011. $(fields[i]).removeData('bv.dfs.' + validator);
  1012. }
  1013. }
  1014. // Mark field as not validated yet
  1015. this.updateStatus(field, this.STATUS_NOT_VALIDATED);
  1016. if (resetFormData) {
  1017. type = fields.attr('type');
  1018. ('radio' == type || 'checkbox' == type) ? fields.removeAttr('checked').removeAttr('selected') : fields.val('');
  1019. }
  1020. }
  1021. this.$invalidFields = $([]);
  1022. this.$submitButton = null;
  1023. // Enable submit buttons
  1024. this.disableSubmitButtons(false);
  1025. return this;
  1026. },
  1027. /**
  1028. * Enable/Disable all validators to given field
  1029. *
  1030. * @param {String} field The field name
  1031. * @param {Boolean} enabled Enable/Disable field validators
  1032. * @returns {BootstrapValidator}
  1033. */
  1034. enableFieldValidators: function(field, enabled) {
  1035. this.options.fields[field]['enabled'] = enabled;
  1036. this.updateStatus(field, this.STATUS_NOT_VALIDATED);
  1037. return this;
  1038. },
  1039. /**
  1040. * Destroy the plugin
  1041. * It will remove all error messages, feedback icons and turn off the events
  1042. */
  1043. destroy: function() {
  1044. var field, fields, $field, validator, $icon, container;
  1045. for (field in this.options.fields) {
  1046. fields = this.getFieldElements(field);
  1047. container = this.options.fields[field].container || this.options.container;
  1048. for (var i = 0; i < fields.length; i++) {
  1049. $field = $(fields[i]);
  1050. $field
  1051. // Remove all error messages
  1052. .data('bv.messages')
  1053. .find('.help-block[data-bv-validator][data-bv-for="' + field + '"]').remove().end()
  1054. .end()
  1055. .removeData('bv.messages')
  1056. // Remove feedback classes
  1057. .parents('.form-group')
  1058. .removeClass('has-feedback has-error has-success')
  1059. .end()
  1060. // Turn off events
  1061. .off('.bv')
  1062. .removeAttr('data-bv-field');
  1063. // Remove feedback icons, tooltip/popover container
  1064. $icon = $field.parents('.form-group').find('i[data-bv-icon-for="' + field + '"]');
  1065. if ($icon) {
  1066. switch (container) {
  1067. case 'tooltip':
  1068. $icon.tooltip('destroy').remove();
  1069. break;
  1070. case 'popover':
  1071. $icon.popover('destroy').remove();
  1072. break;
  1073. default:
  1074. $icon.remove();
  1075. break;
  1076. }
  1077. }
  1078. for (validator in this.options.fields[field].validators) {
  1079. $field.removeData('bv.result.' + validator).removeData('bv.dfs.' + validator);
  1080. }
  1081. }
  1082. }
  1083. // Enable submit buttons
  1084. this.disableSubmitButtons(false);
  1085. this.$form
  1086. .removeClass(this.options.elementClass)
  1087. .off('.bv')
  1088. .removeData('bootstrapValidator')
  1089. // Remove generated hidden elements
  1090. .find('[data-bv-submit-hidden]').remove();
  1091. }
  1092. };
  1093. // Plugin definition
  1094. $.fn.bootstrapValidator = function(option) {
  1095. var params = arguments;
  1096. return this.each(function() {
  1097. var $this = $(this),
  1098. data = $this.data('bootstrapValidator'),
  1099. options = 'object' == typeof option && option;
  1100. if (!data) {
  1101. data = new BootstrapValidator(this, options);
  1102. $this.data('bootstrapValidator', data);
  1103. }
  1104. // Allow to call plugin method
  1105. if ('string' == typeof option) {
  1106. data[option].apply(data, Array.prototype.slice.call(params, 1));
  1107. }
  1108. });
  1109. };
  1110. // Available validators
  1111. $.fn.bootstrapValidator.validators = {};
  1112. $.fn.bootstrapValidator.Constructor = BootstrapValidator;
  1113. // Helper methods, which can be used in validator class
  1114. $.fn.bootstrapValidator.helpers = {
  1115. /**
  1116. * Validate a date
  1117. *
  1118. * @param {Number} year The full year in 4 digits
  1119. * @param {Number} month The month number
  1120. * @param {Number} day The day number
  1121. * @param {Boolean} [notInFuture] If true, the date must not be in the future
  1122. * @returns {Boolean}
  1123. */
  1124. date: function(year, month, day, notInFuture) {
  1125. if (isNaN(year) || isNaN(month) || isNaN(day)) {
  1126. return false;
  1127. }
  1128. if (year < 1000 || year > 9999 || month == 0 || month > 12) {
  1129. return false;
  1130. }
  1131. var numDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  1132. // Update the number of days in Feb of leap year
  1133. if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
  1134. numDays[1] = 29;
  1135. }
  1136. // Check the day
  1137. if (day < 0 || day > numDays[month - 1]) {
  1138. return false;
  1139. }
  1140. if (notInFuture === true) {
  1141. var currentDate = new Date(),
  1142. currentYear = currentDate.getFullYear(),
  1143. currentMonth = currentDate.getMonth(),
  1144. currentDay = currentDate.getDate();
  1145. return (year < currentYear
  1146. || (year == currentYear && month - 1 < currentMonth)
  1147. || (year == currentYear && month - 1 == currentMonth && day < currentDay));
  1148. }
  1149. return true;
  1150. },
  1151. /**
  1152. * Implement Luhn validation algorithm
  1153. * Credit to https://gist.github.com/ShirtlessKirk/2134376
  1154. *
  1155. * @see http://en.wikipedia.org/wiki/Luhn
  1156. * @param {String} value
  1157. * @returns {Boolean}
  1158. */
  1159. luhn: function(value) {
  1160. var length = value.length,
  1161. mul = 0,
  1162. prodArr = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]],
  1163. sum = 0;
  1164. while (length--) {
  1165. sum += prodArr[mul][parseInt(value.charAt(length), 10)];
  1166. mul ^= 1;
  1167. }
  1168. return (sum % 10 === 0 && sum > 0);
  1169. },
  1170. /**
  1171. * Implement modulus 11, 10 (ISO 7064) algorithm
  1172. *
  1173. * @param {String} value
  1174. * @returns {Boolean}
  1175. */
  1176. mod_11_10: function(value) {
  1177. var check = 5,
  1178. length = value.length;
  1179. for (var i = 0; i < length; i++) {
  1180. check = (((check || 10) * 2) % 11 + parseInt(value.charAt(i), 10)) % 10;
  1181. }
  1182. return (check == 1);
  1183. },
  1184. /**
  1185. * Implements Mod 37, 36 (ISO 7064) algorithm
  1186. * Usages:
  1187. * mod_37_36('A12425GABC1234002M')
  1188. * mod_37_36('002006673085', '0123456789')
  1189. *
  1190. * @param {String} value
  1191. * @param {String} alphabet
  1192. * @returns {Boolean}
  1193. */
  1194. mod_37_36: function(value, alphabet) {
  1195. alphabet = alphabet || '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  1196. var modulus = alphabet.length,
  1197. length = value.length,
  1198. check = Math.floor(modulus / 2);
  1199. for (var i = 0; i < length; i++) {
  1200. check = (((check || modulus) * 2) % (modulus + 1) + alphabet.indexOf(value.charAt(i))) % modulus;
  1201. }
  1202. return (check == 1);
  1203. }
  1204. };
  1205. }(window.jQuery));