bootstrapValidator.js 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  1. /**
  2. * BootstrapValidator (https://github.com/nghuuphuoc/bootstrapvalidator)
  3. *
  4. * A jQuery plugin to validate form fields. 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.$invalidField = null; // First invalid field
  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 field will not be live validated if its length is less than this number of characters
  46. threshold: null,
  47. // Indicate fields which won't be validated
  48. // By default, the plugin will not validate the following kind of fields:
  49. // - disabled
  50. // - hidden
  51. // - invisible
  52. //
  53. // The setting consists of jQuery filters. Accept 3 formats:
  54. // - A string. Use a comma to separate filter
  55. // - An array. Each element is a filter
  56. // - An array. Each element can be a callback function
  57. // function($field, validator) {
  58. // $field is jQuery object representing the field element
  59. // validator is the BootstrapValidator instance
  60. // return true or false;
  61. // }
  62. //
  63. // The 3 following settings are equivalent:
  64. //
  65. // 1) ':disabled, :hidden, :not(:visible)'
  66. // 2) [':disabled', ':hidden', ':not(:visible)']
  67. // 3) [':disabled', ':hidden', function($field) {
  68. // return !$field.is(':visible');
  69. // }]
  70. excluded: [':disabled', ':hidden', ':not(:visible)'],
  71. // Shows ok/error/loading icons based on the field validity.
  72. // This feature requires Bootstrap v3.1.0 or later (http://getbootstrap.com/css/#forms-control-validation).
  73. // Since Bootstrap doesn't provide any methods to know its version, this option cannot be on/off automatically.
  74. // In other word, to use this feature you have to upgrade your Bootstrap to v3.1.0 or later.
  75. //
  76. // Examples:
  77. // - Use Glyphicons icons:
  78. // feedbackIcons: {
  79. // valid: 'glyphicon glyphicon-ok',
  80. // invalid: 'glyphicon glyphicon-remove',
  81. // validating: 'glyphicon glyphicon-refresh'
  82. // }
  83. // - Use FontAwesome icons:
  84. // feedbackIcons: {
  85. // valid: 'fa fa-check',
  86. // invalid: 'fa fa-times',
  87. // validating: 'fa fa-refresh'
  88. // }
  89. feedbackIcons: {
  90. valid: null,
  91. invalid: null,
  92. validating: null
  93. },
  94. // The submit buttons selector
  95. // These buttons will be disabled to prevent the valid form from multiple submissions
  96. submitButtons: 'button[type="submit"]',
  97. // The custom submit handler
  98. // It will prevent the form from the default submission
  99. //
  100. // submitHandler: function(validator, form) {
  101. // - validator is the BootstrapValidator instance
  102. // - form is the jQuery object present the current form
  103. // }
  104. submitHandler: null,
  105. // Live validating option
  106. // Can be one of 3 values:
  107. // - enabled: The plugin validates fields as soon as they are changed
  108. // - disabled: Disable the live validating. The error messages are only shown after the form is submitted
  109. // - submitted: The live validating is enabled after the form is submitted
  110. live: 'enabled',
  111. // Map the field name with validator rules
  112. fields: null
  113. };
  114. BootstrapValidator.prototype = {
  115. constructor: BootstrapValidator,
  116. /**
  117. * Init form
  118. */
  119. _init: function() {
  120. var that = this,
  121. options = {
  122. excluded: this.$form.attr('data-bv-excluded'),
  123. trigger: this.$form.attr('data-bv-trigger'),
  124. message: this.$form.attr('data-bv-message'),
  125. submitButtons: this.$form.attr('data-bv-submitbuttons'),
  126. threshold: this.$form.attr('data-bv-threshold'),
  127. live: this.$form.attr('data-bv-live'),
  128. fields: {},
  129. feedbackIcons: {
  130. valid: this.$form.attr('data-bv-feedbackicons-valid'),
  131. invalid: this.$form.attr('data-bv-feedbackicons-invalid'),
  132. validating: this.$form.attr('data-bv-feedbackicons-validating')
  133. }
  134. },
  135. validator,
  136. v, // Validator name
  137. enabled,
  138. optionName,
  139. optionValue,
  140. html5AttrName,
  141. html5Attrs;
  142. this.$form
  143. // Disable client side validation in HTML 5
  144. .attr('novalidate', 'novalidate')
  145. .addClass(this.options.elementClass)
  146. // Disable the default submission first
  147. .on('submit.bv', function(e) {
  148. e.preventDefault();
  149. that.validate();
  150. })
  151. .on('click', this.options.submitButtons, function() {
  152. that.$submitButton = $(this);
  153. // The user just click the submit button
  154. that._submitIfValid = true;
  155. })
  156. // Find all fields which have either "name" or "data-bv-field" attribute
  157. .find('[name], [data-bv-field]').each(function() {
  158. var $field = $(this);
  159. if (that._isExcluded($field)) {
  160. return;
  161. }
  162. var field = $field.attr('name') || $field.attr('data-bv-field'),
  163. validators = {};
  164. for (v in $.fn.bootstrapValidator.validators) {
  165. validator = $.fn.bootstrapValidator.validators[v];
  166. enabled = $field.attr('data-bv-' + v.toLowerCase()) + '';
  167. html5Attrs = ('function' == typeof validator.enableByHtml5) ? validator.enableByHtml5($(this)) : null;
  168. if ((html5Attrs && enabled != 'false')
  169. || (html5Attrs !== true && ('' == enabled || 'true' == enabled)))
  170. {
  171. // Try to parse the options via attributes
  172. validator.html5Attributes = validator.html5Attributes || { message: 'message' };
  173. validators[v] = $.extend({}, html5Attrs == true ? {} : html5Attrs, validators[v]);
  174. for (html5AttrName in validator.html5Attributes) {
  175. optionName = validator.html5Attributes[html5AttrName];
  176. optionValue = $field.attr('data-bv-' + v.toLowerCase() + '-' + html5AttrName);
  177. if (optionValue) {
  178. if ('true' == optionValue) {
  179. optionValue = true;
  180. } else if ('false' == optionValue) {
  181. optionValue = false;
  182. }
  183. validators[v][optionName] = optionValue;
  184. }
  185. }
  186. }
  187. }
  188. var opts = {
  189. trigger: $field.attr('data-bv-trigger'),
  190. message: $field.attr('data-bv-message'),
  191. container: $field.attr('data-bv-container'),
  192. selector: $field.attr('data-bv-selector'),
  193. threshold: $field.attr('data-bv-threshold'),
  194. validators: validators
  195. };
  196. // Check if there is any validators set using HTML attributes
  197. if (!$.isEmptyObject(opts)) {
  198. $field.attr('data-bv-field', field);
  199. options.fields[field] = $.extend({}, opts, options.fields[field]);
  200. }
  201. });
  202. this.options = $.extend(true, this.options, options);
  203. if ('string' == typeof this.options.excluded) {
  204. this.options.excluded = $.map(this.options.excluded.split(','), function(item) {
  205. // Trim the spaces
  206. return $.trim(item);
  207. });
  208. }
  209. for (var field in this.options.fields) {
  210. this._initField(field);
  211. }
  212. },
  213. /**
  214. * Init field
  215. *
  216. * @param {String} field The field name
  217. */
  218. _initField: function(field) {
  219. if (this.options.fields[field] == null || this.options.fields[field].validators == null) {
  220. return;
  221. }
  222. var fields = this.getFieldElements(field);
  223. // We don't need to validate non-existing fields
  224. if (fields == []) {
  225. delete this.options.fields[field];
  226. return;
  227. }
  228. for (var validatorName in this.options.fields[field].validators) {
  229. if (!$.fn.bootstrapValidator.validators[validatorName]) {
  230. delete this.options.fields[field].validators[validatorName];
  231. }
  232. }
  233. if (this.options.fields[field]['enabled'] == null) {
  234. this.options.fields[field]['enabled'] = true;
  235. }
  236. for (var i = 0; i < fields.length; i++) {
  237. this._initFieldElement($(fields[i]));
  238. }
  239. },
  240. /**
  241. * Init field element
  242. *
  243. * @param {jQuery} $field The field element
  244. */
  245. _initFieldElement: function($field) {
  246. var that = this,
  247. field = $field.attr('name') || $field.attr('data-bv-field'),
  248. fields = this.getFieldElements(field),
  249. index = fields.index($field),
  250. type = $field.attr('type'),
  251. total = fields.length,
  252. updateAll = (total == 1) || ('radio' == type) || ('checkbox' == type),
  253. $parent = $field.parents('.form-group'),
  254. // Allow user to indicate where the error messages are shown
  255. $message = this.options.fields[field].container ? $parent.find(this.options.fields[field].container) : this._getMessageContainer($field);
  256. // Remove all error messages and feedback icons
  257. $message.find('.help-block[data-bv-validator]').remove();
  258. $parent.find('i[data-bv-field]').remove();
  259. // Set the attribute to indicate the fields which are defined by selector
  260. if (!$field.attr('data-bv-field')) {
  261. $field.attr('data-bv-field', field);
  262. }
  263. // Whenever the user change the field value, mark it as not validated yet
  264. var event = ('radio' == type || 'checkbox' == type || 'file' == type || 'SELECT' == $field.get(0).tagName) ? 'change' : this._changeEvent;
  265. $field.off(event + '.update.bv').on(event + '.update.bv', function() {
  266. // Reset the flag
  267. that._submitIfValid = false;
  268. that.updateElementStatus($(this), that.STATUS_NOT_VALIDATED);
  269. });
  270. // Create help block elements for showing the error messages
  271. $field.data('bv.messages', $message);
  272. for (var validatorName in this.options.fields[field].validators) {
  273. $field.data('bv.result.' + validatorName, this.STATUS_NOT_VALIDATED);
  274. if (!updateAll || index == total - 1) {
  275. $('<small/>')
  276. .css('display', 'none')
  277. .attr('data-bv-validator', validatorName)
  278. .html(this.options.fields[field].validators[validatorName].message || this.options.fields[field].message || this.options.message)
  279. .addClass('help-block')
  280. .appendTo($message);
  281. }
  282. }
  283. // Prepare the feedback icons
  284. // Available from Bootstrap 3.1 (http://getbootstrap.com/css/#forms-control-validation)
  285. if (this.options.feedbackIcons
  286. && this.options.feedbackIcons.validating && this.options.feedbackIcons.invalid && this.options.feedbackIcons.valid
  287. && (!updateAll || index == total - 1))
  288. {
  289. $parent.removeClass('has-success').removeClass('has-error').addClass('has-feedback');
  290. var $icon = $('<i/>').css('display', 'none').addClass('form-control-feedback').attr('data-bv-field', field).insertAfter($field);
  291. // The feedback icon does not render correctly if there is no label
  292. // https://github.com/twbs/bootstrap/issues/12873
  293. if ($parent.find('label').length == 0) {
  294. $icon.css('top', 0);
  295. }
  296. }
  297. // Set live mode
  298. var trigger = this.options.fields[field].trigger || this.options.trigger || event,
  299. events = $.map(trigger.split(' '), function(item) {
  300. return item + '.live.bv';
  301. }).join(' ');
  302. switch (this.options.live) {
  303. case 'submitted':
  304. break;
  305. case 'disabled':
  306. $field.off(events);
  307. break;
  308. case 'enabled':
  309. default:
  310. $field.off(events).on(events, function() {
  311. that.validateFieldElement($(this));
  312. });
  313. break;
  314. }
  315. },
  316. /**
  317. * Get the element to place the error messages
  318. *
  319. * @param {jQuery} $field The field element
  320. * @returns {jQuery}
  321. */
  322. _getMessageContainer: function($field) {
  323. var $parent = $field.parent();
  324. if ($parent.hasClass('form-group')) {
  325. return $parent;
  326. }
  327. var cssClasses = $parent.attr('class');
  328. if (!cssClasses) {
  329. return this._getMessageContainer($parent);
  330. }
  331. cssClasses = cssClasses.split(' ');
  332. var n = cssClasses.length;
  333. for (var i = 0; i < n; i++) {
  334. if (/^col-(xs|sm|md|lg)-\d+$/.test(cssClasses[i]) || /^col-(xs|sm|md|lg)-offset-\d+$/.test(cssClasses[i])) {
  335. return $parent;
  336. }
  337. }
  338. return this._getMessageContainer($parent);
  339. },
  340. /**
  341. * Called when all validations are completed
  342. */
  343. _submit: function() {
  344. var isValid = this.isValid(),
  345. eventType = isValid ? 'success.form.bv' : 'error.form.bv',
  346. e = $.Event(eventType);
  347. this.$form.trigger(e);
  348. // Call default handler
  349. // Check if whether the submit button is clicked
  350. if (this.$submitButton) {
  351. isValid ? this._onSuccess(e) : this._onError(e);
  352. }
  353. },
  354. /**
  355. * Check if the field is excluded.
  356. * Returning true means that the field will not be validated
  357. *
  358. * @param {jQuery} $field The field element
  359. * @return {Boolean}
  360. */
  361. _isExcluded: function($field) {
  362. if (this.options.excluded) {
  363. for (var i in this.options.excluded) {
  364. if (('string' == typeof this.options.excluded[i] && $field.is(this.options.excluded[i]))
  365. || ('function' == typeof this.options.excluded[i] && this.options.excluded[i].call(this, $field, this) == true))
  366. {
  367. return true;
  368. }
  369. }
  370. }
  371. return false;
  372. },
  373. // --- Events ---
  374. /**
  375. * The default handler of error.form.bv event.
  376. * It will be called when there is a invalid field
  377. *
  378. * @param {jQuery.Event} e The jQuery event object
  379. */
  380. _onError: function(e) {
  381. if (e.isDefaultPrevented()) {
  382. return;
  383. }
  384. if ('submitted' == this.options.live) {
  385. // Enable live mode
  386. this.options.live = 'enabled';
  387. var that = this;
  388. for (var field in this.options.fields) {
  389. (function(f) {
  390. var fields = that.getFieldElements(f);
  391. if (fields.length) {
  392. var type = $(fields[0]).attr('type'),
  393. event = ('radio' == type || 'checkbox' == type || 'file' == type || 'SELECT' == $(fields[0]).get(0).tagName) ? 'change' : that._changeEvent,
  394. trigger = that.options.fields[field].trigger || that.options.trigger || event,
  395. events = $.map(trigger.split(' '), function(item) {
  396. return item + '.live.bv';
  397. }).join(' ');
  398. for (var i = 0; i < fields.length; i++) {
  399. $(fields[i]).off(events).on(events, function() {
  400. that.validateFieldElement($(this));
  401. });
  402. }
  403. }
  404. })(field);
  405. }
  406. }
  407. // Focus to the first invalid field
  408. if (this.$invalidField) {
  409. // Activate the tab containing the invalid field if exists
  410. var $tab = this.$invalidField.parents('.tab-pane'),
  411. tabId;
  412. if ($tab && (tabId = $tab.attr('id'))) {
  413. $('a[href="#' + tabId + '"][data-toggle="tab"]').trigger('click.bs.tab.data-api');
  414. }
  415. this.$invalidField.focus();
  416. }
  417. },
  418. /**
  419. * The default handler of success.form.bv event.
  420. * It will be called when all the fields are valid
  421. *
  422. * @param {jQuery.Event} e The jQuery event object
  423. */
  424. _onSuccess: function(e) {
  425. if (e.isDefaultPrevented()) {
  426. return;
  427. }
  428. // Call the custom submission if enabled
  429. if (this.options.submitHandler && 'function' == typeof this.options.submitHandler) {
  430. // If you want to submit the form inside your submit handler, please call defaultSubmit() method
  431. this.options.submitHandler.call(this, this, this.$form, this.$submitButton);
  432. } else {
  433. this.disableSubmitButtons(true).defaultSubmit();
  434. }
  435. },
  436. /**
  437. * Called after validating a field element
  438. *
  439. * @param {jQuery} $field The field element
  440. */
  441. _onValidateFieldCompleted: function($field) {
  442. var field = $field.attr('data-bv-field'),
  443. validators = this.options.fields[field].validators,
  444. counter = {},
  445. numValidators = 0;
  446. counter[this.STATUS_NOT_VALIDATED] = 0;
  447. counter[this.STATUS_VALIDATING] = 0;
  448. counter[this.STATUS_INVALID] = 0;
  449. counter[this.STATUS_VALID] = 0;
  450. for (var validatorName in validators) {
  451. numValidators++;
  452. var result = $field.data('bv.result.' + validatorName);
  453. if (result) {
  454. counter[result]++;
  455. }
  456. }
  457. if (counter[this.STATUS_VALID] == numValidators) {
  458. this.$form.trigger($.Event('success.field.bv'), [field, $field]);
  459. }
  460. // If all validators are completed and there is at least one validator which doesn't pass
  461. else if (counter[this.STATUS_NOT_VALIDATED] == 0 && counter[this.STATUS_VALIDATING] == 0 && counter[this.STATUS_INVALID] > 0) {
  462. this.$form.trigger($.Event('error.field.bv'), [field, $field]);
  463. }
  464. },
  465. // --- Public methods ---
  466. /**
  467. * Retrieve the field elements by given name
  468. *
  469. * @param {String} field The field name
  470. * @returns {null|jQuery[]}
  471. */
  472. getFieldElements: function(field) {
  473. if (!this._cacheFields[field]) {
  474. this._cacheFields[field] = this.options.fields[field].selector
  475. ? $(this.options.fields[field].selector)
  476. : this.$form.find('[name="' + field + '"]');
  477. }
  478. return this._cacheFields[field];
  479. },
  480. /**
  481. * Disable/enable submit buttons
  482. *
  483. * @param {Boolean} disabled Can be true or false
  484. * @returns {BootstrapValidator}
  485. */
  486. disableSubmitButtons: function(disabled) {
  487. if (!disabled) {
  488. this.$form.find(this.options.submitButtons).removeAttr('disabled');
  489. } else if (this.options.live != 'disabled') {
  490. // Don't disable if the live validating mode is disabled
  491. this.$form.find(this.options.submitButtons).attr('disabled', 'disabled');
  492. }
  493. return this;
  494. },
  495. /**
  496. * Validate the form
  497. *
  498. * @return {BootstrapValidator}
  499. */
  500. validate: function() {
  501. if (!this.options.fields) {
  502. return this;
  503. }
  504. this.disableSubmitButtons(true);
  505. for (var field in this.options.fields) {
  506. this.validateField(field);
  507. }
  508. this._submit();
  509. return this;
  510. },
  511. /**
  512. * Validate given field
  513. *
  514. * @param {String} field The field name
  515. * @returns {BootstrapValidator}
  516. */
  517. validateField: function(field) {
  518. var fields = this.getFieldElements(field),
  519. type = fields.attr('type'),
  520. n = (('radio' == type) || ('checkbox' == type)) ? 1 : fields.length;
  521. for (var i = 0; i < n; i++) {
  522. this.validateFieldElement($(fields[i]));
  523. }
  524. return this;
  525. },
  526. /**
  527. * Validate field element
  528. *
  529. * @param {jQuery} $field The field element
  530. * @returns {BootstrapValidator}
  531. */
  532. validateFieldElement: function($field) {
  533. var that = this,
  534. field = $field.attr('data-bv-field'),
  535. fields = this.getFieldElements(field),
  536. type = $field.attr('type'),
  537. updateAll = (fields && fields.length == 1) || ('radio' == type) || ('checkbox' == type),
  538. validators = this.options.fields[field].validators,
  539. validatorName,
  540. validateResult;
  541. if (!this.options.fields[field]['enabled'] || this._isExcluded($field)) {
  542. return this;
  543. }
  544. for (validatorName in validators) {
  545. if ($field.data('bv.dfs.' + validatorName)) {
  546. $field.data('bv.dfs.' + validatorName).reject();
  547. }
  548. // Don't validate field if it is already done
  549. var result = $field.data('bv.result.' + validatorName);
  550. if (result == this.STATUS_VALID || result == this.STATUS_INVALID) {
  551. this._onValidateFieldCompleted($field);
  552. continue;
  553. }
  554. $field.data('bv.result.' + validatorName, this.STATUS_VALIDATING);
  555. validateResult = $.fn.bootstrapValidator.validators[validatorName].validate(this, $field, validators[validatorName]);
  556. if ('object' == typeof validateResult) {
  557. updateAll ? this.updateStatus(field, this.STATUS_VALIDATING, validatorName)
  558. : this.updateElementStatus($field, this.STATUS_VALIDATING, validatorName);
  559. $field.data('bv.dfs.' + validatorName, validateResult);
  560. validateResult.done(function($f, v, isValid) {
  561. // v is validator name
  562. $f.removeData('bv.dfs.' + v);
  563. updateAll ? that.updateStatus($f.attr('data-bv-field'), isValid ? that.STATUS_VALID : that.STATUS_INVALID, v)
  564. : that.updateElementStatus($f, isValid ? that.STATUS_VALID : that.STATUS_INVALID, v);
  565. if (isValid && that._submitIfValid == true) {
  566. // If a remote validator returns true and the form is ready to submit, then do it
  567. that._submit();
  568. }
  569. });
  570. } else if ('boolean' == typeof validateResult) {
  571. updateAll ? this.updateStatus(field, validateResult ? this.STATUS_VALID : this.STATUS_INVALID, validatorName)
  572. : this.updateElementStatus($field, validateResult ? this.STATUS_VALID : this.STATUS_INVALID, validatorName);
  573. }
  574. }
  575. return this;
  576. },
  577. /**
  578. * Update all validating results of elements which have the same field name
  579. *
  580. * @param {String} field The field name
  581. * @param {String} status The status. Can be 'NOT_VALIDATED', 'VALIDATING', 'INVALID' or 'VALID'
  582. * @param {String} [validatorName] The validator name. If null, the method updates validity result for all validators
  583. * @return {BootstrapValidator}
  584. */
  585. updateStatus: function(field, status, validatorName) {
  586. var fields = this.getFieldElements(field),
  587. type = fields.attr('type'),
  588. n = (('radio' == type) || ('checkbox' == type)) ? 1 : fields.length;
  589. for (var i = 0; i < n; i++) {
  590. this.updateElementStatus($(fields[i]), status, validatorName);
  591. }
  592. return this;
  593. },
  594. /**
  595. * Update validating result of given element
  596. *
  597. * @param {jQuery} $field The field element
  598. * @param {String} status The status. Can be 'NOT_VALIDATED', 'VALIDATING', 'INVALID' or 'VALID'
  599. * @param {String} [validatorName] The validator name. If null, the method updates validity result for all validators
  600. * @return {BootstrapValidator}
  601. */
  602. updateElementStatus: function($field, status, validatorName) {
  603. var that = this,
  604. field = $field.attr('data-bv-field'),
  605. $parent = $field.parents('.form-group'),
  606. $message = $field.data('bv.messages'),
  607. $errors = $message.find('.help-block[data-bv-validator]'),
  608. $icon = $parent.find('.form-control-feedback[data-bv-field="' + field + '"]');
  609. // Update status
  610. if (validatorName) {
  611. $field.data('bv.result.' + validatorName, status);
  612. } else {
  613. for (var v in this.options.fields[field].validators) {
  614. $field.data('bv.result.' + v, status);
  615. }
  616. }
  617. // Determine the tab containing the element
  618. var $tabPane = $field.parents('.tab-pane'),
  619. tabId,
  620. $tab;
  621. if ($tabPane && (tabId = $tabPane.attr('id'))) {
  622. $tab = $('a[href="#' + tabId + '"][data-toggle="tab"]').parent();
  623. }
  624. // Show/hide error elements and feedback icons
  625. validatorName ? $errors.filter('.help-block[data-bv-validator="' + validatorName + '"]').attr('data-bv-result', status) : $errors.attr('data-bv-result', status);
  626. switch (status) {
  627. case this.STATUS_VALIDATING:
  628. this.disableSubmitButtons(true);
  629. $parent.removeClass('has-success').removeClass('has-error');
  630. // TODO: Show validating message
  631. validatorName ? $errors.filter('.help-block[data-bv-validator="' + validatorName + '"]').hide() : $errors.hide();
  632. if ($icon) {
  633. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).addClass(this.options.feedbackIcons.validating).show();
  634. }
  635. if ($tab) {
  636. $tab.removeClass('bv-tab-success').removeClass('bv-tab-error');
  637. }
  638. break;
  639. case this.STATUS_INVALID:
  640. this.disableSubmitButtons(true);
  641. $parent.removeClass('has-success').addClass('has-error');
  642. validatorName ? $errors.filter('[data-bv-validator="' + validatorName + '"]').show() : $errors.show();
  643. if ($icon) {
  644. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.validating).addClass(this.options.feedbackIcons.invalid).show();
  645. }
  646. if ($tab) {
  647. $tab.removeClass('bv-tab-success').addClass('bv-tab-error');
  648. }
  649. break;
  650. case this.STATUS_VALID:
  651. validatorName ? $errors.filter('[data-bv-validator="' + validatorName + '"]').hide() : $errors.hide();
  652. // If the field is valid (passes all validators)
  653. var validField = $errors.filter(function() {
  654. var v = $(this).attr('data-bv-validator');
  655. return $field.data('bv.result.' + v) != that.STATUS_VALID;
  656. }).length == 0;
  657. this.disableSubmitButtons(validField ? false : true);
  658. if ($icon) {
  659. $icon
  660. .removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).removeClass(this.options.feedbackIcons.valid)
  661. .addClass(validField ? this.options.feedbackIcons.valid : this.options.feedbackIcons.invalid)
  662. .show();
  663. }
  664. // Check if all elements in given container are valid
  665. var isValidContainer = function($container) {
  666. return $container
  667. .find('.help-block[data-bv-validator]')
  668. .filter(function() {
  669. var display = $(this).css('display'), v = $(this).attr('data-bv-validator');
  670. return ('block' == display) || ($field.data('bv.result.' + v) && $field.data('bv.result.' + v) != that.STATUS_VALID);
  671. })
  672. .length == 0;
  673. };
  674. $parent.removeClass('has-error has-success').addClass(isValidContainer($parent) ? 'has-success' : 'has-error');
  675. if ($tab) {
  676. $tab.removeClass('bv-tab-success').removeClass('bv-tab-error').addClass(isValidContainer($tabPane) ? 'bv-tab-success' : 'bv-tab-error');
  677. }
  678. break;
  679. case this.STATUS_NOT_VALIDATED:
  680. default:
  681. this.disableSubmitButtons(false);
  682. $parent.removeClass('has-success').removeClass('has-error');
  683. validatorName ? $errors.filter('.help-block[data-bv-validator="' + validatorName + '"]').hide() : $errors.hide();
  684. if ($icon) {
  685. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).hide();
  686. }
  687. if ($tab) {
  688. $tab.removeClass('bv-tab-success').removeClass('bv-tab-error');
  689. }
  690. break;
  691. }
  692. this._onValidateFieldCompleted($field);
  693. return this;
  694. },
  695. /**
  696. * Check the form validity
  697. *
  698. * @returns {Boolean}
  699. */
  700. isValid: function() {
  701. var fields, field, $field,
  702. type, status, validatorName,
  703. n, i;
  704. for (field in this.options.fields) {
  705. if (this.options.fields[field] == null || !this.options.fields[field]['enabled']) {
  706. continue;
  707. }
  708. fields = this.getFieldElements(field);
  709. type = fields.attr('type');
  710. n = (('radio' == type) || ('checkbox' == type)) ? 1 : fields.length;
  711. for (i = 0; i < n; i++) {
  712. $field = $(fields[i]);
  713. if (this._isExcluded($field)) {
  714. continue;
  715. }
  716. for (validatorName in this.options.fields[field].validators) {
  717. status = $field.data('bv.result.' + validatorName);
  718. if (status == this.STATUS_NOT_VALIDATED || status == this.STATUS_VALIDATING) {
  719. return false;
  720. }
  721. if (status == this.STATUS_INVALID) {
  722. this.$invalidField = $field;
  723. return false;
  724. }
  725. }
  726. }
  727. }
  728. return true;
  729. },
  730. /**
  731. * Submit the form using default submission.
  732. * It also does not perform any validations when submitting the form
  733. *
  734. * It might be used when you want to submit the form right inside the submitHandler()
  735. */
  736. defaultSubmit: function() {
  737. this.$form.off('submit.bv').submit();
  738. },
  739. // Useful APIs which aren't used internally
  740. /**
  741. * Add new field element
  742. *
  743. * @param {jQuery} $field The field element
  744. * @param {Object} options The field options
  745. * @returns {BootstrapValidator}
  746. */
  747. addFieldElement: function($field, options) {
  748. var field = $field.attr('name') || $field.attr('data-bv-field'),
  749. type = $field.attr('type'),
  750. isNewField = !this._cacheFields[field];
  751. // Update cache
  752. if (!isNewField && this._cacheFields[field].index($field) == -1) {
  753. this._cacheFields[field] = this._cacheFields[field].add($field);
  754. }
  755. if ('checkbox' == type || 'radio' == type || isNewField) {
  756. this._initField(field);
  757. } else {
  758. this._initFieldElement($field);
  759. }
  760. return this;
  761. },
  762. /**
  763. * Remove given field element
  764. *
  765. * @param {jQuery} $field The field element
  766. * @returns {BootstrapValidator}
  767. */
  768. removeFieldElement: function($field) {
  769. var field = $field.attr('name') || $field.attr('data-bv-field'),
  770. type = $field.attr('type'),
  771. index = this._cacheFields[field].index($field);
  772. (index == -1) ? (delete this._cacheFields[field]) : this._cacheFields[field].splice(index, 1);
  773. if ('checkbox' == type || 'radio' == type) {
  774. this._initField(field);
  775. }
  776. return this;
  777. },
  778. /**
  779. * Reset the form
  780. *
  781. * @param {Boolean} resetFormData Reset current form data
  782. * @return {BootstrapValidator}
  783. */
  784. resetForm: function(resetFormData) {
  785. var field, fields, total, type, validator;
  786. for (field in this.options.fields) {
  787. fields = this.getFieldElements(field);
  788. total = fields.length;
  789. for (var i = 0; i < total; i++) {
  790. for (validator in this.options.fields[field].validators) {
  791. $(fields[i]).removeData('bv.dfs.' + validator);
  792. }
  793. }
  794. // Mark field as not validated yet
  795. this.updateStatus(field, this.STATUS_NOT_VALIDATED);
  796. if (resetFormData) {
  797. type = fields.attr('type');
  798. ('radio' == type || 'checkbox' == type) ? fields.removeAttr('checked').removeAttr('selected') : fields.val('');
  799. }
  800. }
  801. this.$invalidField = null;
  802. this.$submitButton = null;
  803. // Enable submit buttons
  804. this.disableSubmitButtons(false);
  805. return this;
  806. },
  807. /**
  808. * Enable/Disable all validators to given field
  809. *
  810. * @param {String} field The field name
  811. * @param {Boolean} enabled Enable/Disable field validators
  812. * @return {BootstrapValidator}
  813. */
  814. enableFieldValidators: function(field, enabled) {
  815. this.options.fields[field]['enabled'] = enabled;
  816. this.updateStatus(field, this.STATUS_NOT_VALIDATED);
  817. return this;
  818. }
  819. };
  820. // Plugin definition
  821. $.fn.bootstrapValidator = function(option, params) {
  822. return this.each(function() {
  823. var $this = $(this),
  824. data = $this.data('bootstrapValidator'),
  825. options = 'object' == typeof option && option;
  826. if (!data) {
  827. data = new BootstrapValidator(this, options);
  828. $this.data('bootstrapValidator', data);
  829. }
  830. // Allow to call plugin method
  831. if ('string' == typeof option) {
  832. data[option](params);
  833. }
  834. });
  835. };
  836. // Available validators
  837. $.fn.bootstrapValidator.validators = {};
  838. $.fn.bootstrapValidator.Constructor = BootstrapValidator;
  839. // Helper methods, which can be used in validator class
  840. $.fn.bootstrapValidator.helpers = {
  841. /**
  842. * Validate a date
  843. *
  844. * @param {Number} year The full year in 4 digits
  845. * @param {Number} month The month number
  846. * @param {Number} day The day number
  847. * @returns {Boolean}
  848. */
  849. date: function(year, month, day) {
  850. if (year < 1000 || year > 9999 || month == 0 || month > 12) {
  851. return false;
  852. }
  853. var numDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  854. // Update the number of days in Feb of leap year
  855. if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
  856. numDays[1] = 29;
  857. }
  858. // Check the day
  859. return (day > 0 && day <= numDays[month - 1]);
  860. },
  861. /**
  862. * Implement Luhn validation algorithm ((http://en.wikipedia.org/wiki/Luhn))
  863. * Credit to https://gist.github.com/ShirtlessKirk/2134376
  864. *
  865. * @param {String} value
  866. * @returns {Boolean}
  867. */
  868. luhn: function(value) {
  869. var length = value.length,
  870. mul = 0,
  871. prodArr = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]],
  872. sum = 0;
  873. while (length--) {
  874. sum += prodArr[mul][parseInt(value.charAt(length), 10)];
  875. mul ^= 1;
  876. }
  877. return (sum % 10 === 0 && sum > 0);
  878. },
  879. /**
  880. * Implement modulus 11, 10 (ISO 7064) algorithm
  881. *
  882. * @param {String} value
  883. * @returns {Boolean}
  884. */
  885. mod_11_10: function(value) {
  886. var check = 5,
  887. length = value.length;
  888. for (var i = 0; i < length; i++) {
  889. check = (((check || 10) * 2) % 11 + parseInt(value.charAt(i), 10)) % 10;
  890. }
  891. return (check == 1);
  892. },
  893. /**
  894. * Implements Mod 37, 36 (ISO 7064) algorithm
  895. * Usages:
  896. * mod_37_36('A12425GABC1234002M')
  897. * mod_37_36('002006673085', '0123456789')
  898. *
  899. * @param {String} value
  900. * @param {String} alphabet
  901. * @returns {Boolean}
  902. */
  903. mod_37_36: function(value, alphabet) {
  904. alphabet = alphabet || '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  905. var modulus = alphabet.length,
  906. length = value.length,
  907. check = Math.floor(modulus / 2);
  908. for (var i = 0; i < length; i++) {
  909. check = (((check || modulus) * 2) % (modulus + 1) + alphabet.indexOf(value.charAt(i))) % modulus;
  910. }
  911. return (check == 1);
  912. }
  913. };
  914. }(window.jQuery));