bootstrapValidator.js 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193
  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: null
  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. validator,
  146. v, // Validator name
  147. enabled,
  148. optionName,
  149. optionValue,
  150. html5AttrName,
  151. html5Attrs;
  152. this.$form
  153. // Disable client side validation in HTML 5
  154. .attr('novalidate', 'novalidate')
  155. .addClass(this.options.elementClass)
  156. // Disable the default submission first
  157. .on('submit.bv', function(e) {
  158. e.preventDefault();
  159. that.validate();
  160. })
  161. .on('click', this.options.submitButtons, function() {
  162. that.$submitButton = $(this);
  163. // The user just click the submit button
  164. that._submitIfValid = true;
  165. })
  166. // Find all fields which have either "name" or "data-bv-field" attribute
  167. .find('[name], [data-bv-field]')
  168. .each(function() {
  169. var $field = $(this);
  170. if (that._isExcluded($field)) {
  171. return;
  172. }
  173. var field = $field.attr('name') || $field.attr('data-bv-field'),
  174. validators = {};
  175. for (v in $.fn.bootstrapValidator.validators) {
  176. validator = $.fn.bootstrapValidator.validators[v];
  177. enabled = $field.attr('data-bv-' + v.toLowerCase()) + '';
  178. html5Attrs = ('function' == typeof validator.enableByHtml5) ? validator.enableByHtml5($(this)) : null;
  179. if ((html5Attrs && enabled != 'false')
  180. || (html5Attrs !== true && ('' == enabled || 'true' == enabled)))
  181. {
  182. // Try to parse the options via attributes
  183. validator.html5Attributes = validator.html5Attributes || { message: 'message' };
  184. validators[v] = $.extend({}, html5Attrs == true ? {} : html5Attrs, validators[v]);
  185. for (html5AttrName in validator.html5Attributes) {
  186. optionName = validator.html5Attributes[html5AttrName];
  187. optionValue = $field.attr('data-bv-' + v.toLowerCase() + '-' + html5AttrName);
  188. if (optionValue) {
  189. if ('true' == optionValue) {
  190. optionValue = true;
  191. } else if ('false' == optionValue) {
  192. optionValue = false;
  193. }
  194. validators[v][optionName] = optionValue;
  195. }
  196. }
  197. }
  198. }
  199. var opts = {
  200. trigger: $field.attr('data-bv-trigger'),
  201. message: $field.attr('data-bv-message'),
  202. container: $field.attr('data-bv-container'),
  203. selector: $field.attr('data-bv-selector'),
  204. threshold: $field.attr('data-bv-threshold'),
  205. validators: validators
  206. };
  207. // Check if there is any validators set using HTML attributes
  208. if (!$.isEmptyObject(opts.validators) && !$.isEmptyObject(opts)) {
  209. $field.attr('data-bv-field', field);
  210. options.fields[field] = $.extend({}, opts, options.fields[field]);
  211. }
  212. })
  213. .end()
  214. // Create hidden inputs to send the submit buttons
  215. .find(this.options.submitButtons)
  216. .each(function() {
  217. $('<input/>')
  218. .attr('type', 'hidden')
  219. .attr('name', $(this).attr('name'))
  220. .val($(this).val())
  221. .appendTo(that.$form);
  222. });
  223. this.options = $.extend(true, this.options, options);
  224. for (var field in this.options.fields) {
  225. this._initField(field);
  226. }
  227. },
  228. /**
  229. * Init field
  230. *
  231. * @param {String} field The field name
  232. */
  233. _initField: function(field) {
  234. if (this.options.fields[field] == null || this.options.fields[field].validators == null) {
  235. return;
  236. }
  237. var fields = this.getFieldElements(field);
  238. // We don't need to validate non-existing fields
  239. if (fields == []) {
  240. delete this.options.fields[field];
  241. return;
  242. }
  243. for (var validatorName in this.options.fields[field].validators) {
  244. if (!$.fn.bootstrapValidator.validators[validatorName]) {
  245. delete this.options.fields[field].validators[validatorName];
  246. }
  247. }
  248. if (this.options.fields[field]['enabled'] == null) {
  249. this.options.fields[field]['enabled'] = true;
  250. }
  251. for (var i = 0; i < fields.length; i++) {
  252. this._initFieldElement($(fields[i]));
  253. }
  254. },
  255. /**
  256. * Init field element
  257. *
  258. * @param {jQuery} $field The field element
  259. */
  260. _initFieldElement: function($field) {
  261. var that = this,
  262. field = $field.attr('name') || $field.attr('data-bv-field'),
  263. fields = this.getFieldElements(field),
  264. index = fields.index($field),
  265. type = $field.attr('type'),
  266. total = fields.length,
  267. updateAll = (total == 1) || ('radio' == type) || ('checkbox' == type),
  268. $parent = $field.parents('.form-group'),
  269. // Allow user to indicate where the error messages are shown
  270. container = this.options.fields[field].container || this.options.container,
  271. $message = (container && ['tooltip', 'popover'].indexOf(container) == -1) ? $(container) : this._getMessageContainer($field);
  272. if (container && ['tooltip', 'popover'].indexOf(container) == -1) {
  273. $message.addClass('has-error');
  274. }
  275. // Remove all error messages and feedback icons
  276. $message.find('.help-block[data-bv-validator][data-bv-for="' + field + '"]').remove();
  277. $parent.find('i[data-bv-icon-for="' + field + '"]').remove();
  278. // Set the attribute to indicate the fields which are defined by selector
  279. if (!$field.attr('data-bv-field')) {
  280. $field.attr('data-bv-field', field);
  281. }
  282. // Whenever the user change the field value, mark it as not validated yet
  283. var event = ('radio' == type || 'checkbox' == type || 'file' == type || 'SELECT' == $field.get(0).tagName) ? 'change' : this._changeEvent;
  284. $field.off(event + '.update.bv').on(event + '.update.bv', function() {
  285. // Reset the flag
  286. that._submitIfValid = false;
  287. that.updateElementStatus($(this), that.STATUS_NOT_VALIDATED);
  288. });
  289. // Create help block elements for showing the error messages
  290. $field.data('bv.messages', $message);
  291. for (var validatorName in this.options.fields[field].validators) {
  292. $field.data('bv.result.' + validatorName, this.STATUS_NOT_VALIDATED);
  293. if (!updateAll || index == total - 1) {
  294. $('<small/>')
  295. .css('display', 'none')
  296. .addClass('help-block')
  297. .attr('data-bv-validator', validatorName)
  298. .attr('data-bv-for', field)
  299. .html(this.options.fields[field].validators[validatorName].message || this.options.fields[field].message || this.options.message)
  300. .appendTo($message);
  301. }
  302. }
  303. // Prepare the feedback icons
  304. // Available from Bootstrap 3.1 (http://getbootstrap.com/css/#forms-control-validation)
  305. if (this.options.feedbackIcons
  306. && this.options.feedbackIcons.validating && this.options.feedbackIcons.invalid && this.options.feedbackIcons.valid
  307. && (!updateAll || index == total - 1))
  308. {
  309. $parent.removeClass('has-success').removeClass('has-error').addClass('has-feedback');
  310. var $icon = $('<i/>').css('display', 'none').addClass('form-control-feedback').attr('data-bv-icon-for', field).insertAfter($field);
  311. // The feedback icon does not render correctly if there is no label
  312. // https://github.com/twbs/bootstrap/issues/12873
  313. if ($parent.find('label').length == 0) {
  314. $icon.css('top', 0);
  315. }
  316. // Fix icons in .form-group > .input-group
  317. if ($parent.find('.input-group-addon').length != 0) {
  318. $icon.css({'top':0, 'z-index':100});
  319. }
  320. }
  321. // Set live mode
  322. var trigger = this.options.fields[field].trigger || this.options.trigger || event,
  323. events = $.map(trigger.split(' '), function(item) {
  324. return item + '.live.bv';
  325. }).join(' ');
  326. switch (this.options.live) {
  327. case 'submitted':
  328. break;
  329. case 'disabled':
  330. $field.off(events);
  331. break;
  332. case 'enabled':
  333. default:
  334. $field.off(events).on(events, function() {
  335. that.validateFieldElement($(this));
  336. });
  337. break;
  338. }
  339. },
  340. /**
  341. * Get the element to place the error messages
  342. *
  343. * @param {jQuery} $field The field element
  344. * @returns {jQuery}
  345. */
  346. _getMessageContainer: function($field) {
  347. var $parent = $field.parent();
  348. if ($parent.hasClass('form-group')) {
  349. return $parent;
  350. }
  351. var cssClasses = $parent.attr('class');
  352. if (!cssClasses) {
  353. return this._getMessageContainer($parent);
  354. }
  355. cssClasses = cssClasses.split(' ');
  356. var n = cssClasses.length;
  357. for (var i = 0; i < n; i++) {
  358. if (/^col-(xs|sm|md|lg)-\d+$/.test(cssClasses[i]) || /^col-(xs|sm|md|lg)-offset-\d+$/.test(cssClasses[i])) {
  359. return $parent;
  360. }
  361. }
  362. return this._getMessageContainer($parent);
  363. },
  364. /**
  365. * Called when all validations are completed
  366. */
  367. _submit: function() {
  368. var isValid = this.isValid(),
  369. eventType = isValid ? 'success.form.bv' : 'error.form.bv',
  370. e = $.Event(eventType);
  371. this.$form.trigger(e);
  372. // Call default handler
  373. // Check if whether the submit button is clicked
  374. if (this.$submitButton) {
  375. isValid ? this._onSuccess(e) : this._onError(e);
  376. }
  377. },
  378. /**
  379. * Check if the field is excluded.
  380. * Returning true means that the field will not be validated
  381. *
  382. * @param {jQuery} $field The field element
  383. * @returns {Boolean}
  384. */
  385. _isExcluded: function($field) {
  386. if (this.options.excluded) {
  387. // Convert to array first
  388. if ('string' == typeof this.options.excluded) {
  389. this.options.excluded = $.map(this.options.excluded.split(','), function(item) {
  390. // Trim the spaces
  391. return $.trim(item);
  392. });
  393. }
  394. var length = this.options.excluded.length;
  395. for (var i = 0; i < length; i++) {
  396. if (('string' == typeof this.options.excluded[i] && $field.is(this.options.excluded[i]))
  397. || ('function' == typeof this.options.excluded[i] && this.options.excluded[i].call(this, $field, this) == true))
  398. {
  399. return true;
  400. }
  401. }
  402. }
  403. return false;
  404. },
  405. // --- Events ---
  406. /**
  407. * The default handler of error.form.bv event.
  408. * It will be called when there is a invalid field
  409. *
  410. * @param {jQuery.Event} e The jQuery event object
  411. */
  412. _onError: function(e) {
  413. if (e.isDefaultPrevented()) {
  414. return;
  415. }
  416. if ('submitted' == this.options.live) {
  417. // Enable live mode
  418. this.options.live = 'enabled';
  419. var that = this;
  420. for (var field in this.options.fields) {
  421. (function(f) {
  422. var fields = that.getFieldElements(f);
  423. if (fields.length) {
  424. var type = $(fields[0]).attr('type'),
  425. event = ('radio' == type || 'checkbox' == type || 'file' == type || 'SELECT' == $(fields[0]).get(0).tagName) ? 'change' : that._changeEvent,
  426. trigger = that.options.fields[field].trigger || that.options.trigger || event,
  427. events = $.map(trigger.split(' '), function(item) {
  428. return item + '.live.bv';
  429. }).join(' ');
  430. for (var i = 0; i < fields.length; i++) {
  431. $(fields[i]).off(events).on(events, function() {
  432. that.validateFieldElement($(this));
  433. });
  434. }
  435. }
  436. })(field);
  437. }
  438. }
  439. // Focus to the first invalid field
  440. var $firstInvalidField = this.$invalidFields.eq(0);
  441. if ($firstInvalidField) {
  442. // Activate the tab containing the invalid field if exists
  443. var $tab = $firstInvalidField.parents('.tab-pane'),
  444. tabId;
  445. if ($tab && (tabId = $tab.attr('id'))) {
  446. $('a[href="#' + tabId + '"][data-toggle="tab"]').trigger('click.bs.tab.data-api');
  447. }
  448. $firstInvalidField.focus();
  449. }
  450. },
  451. /**
  452. * The default handler of success.form.bv event.
  453. * It will be called when all the fields are valid
  454. *
  455. * @param {jQuery.Event} e The jQuery event object
  456. */
  457. _onSuccess: function(e) {
  458. if (e.isDefaultPrevented()) {
  459. return;
  460. }
  461. // Call the custom submission if enabled
  462. if (this.options.submitHandler && 'function' == typeof this.options.submitHandler) {
  463. // If you want to submit the form inside your submit handler, please call defaultSubmit() method
  464. this.options.submitHandler.call(this, this, this.$form, this.$submitButton);
  465. } else {
  466. this.disableSubmitButtons(true).defaultSubmit();
  467. }
  468. },
  469. /**
  470. * Called after validating a field element
  471. *
  472. * @param {jQuery} $field The field element
  473. */
  474. _onValidateFieldCompleted: function($field) {
  475. var field = $field.attr('data-bv-field'),
  476. validators = this.options.fields[field].validators,
  477. counter = {},
  478. numValidators = 0;
  479. counter[this.STATUS_NOT_VALIDATED] = 0;
  480. counter[this.STATUS_VALIDATING] = 0;
  481. counter[this.STATUS_INVALID] = 0;
  482. counter[this.STATUS_VALID] = 0;
  483. for (var validatorName in validators) {
  484. numValidators++;
  485. var result = $field.data('bv.result.' + validatorName);
  486. if (result) {
  487. counter[result]++;
  488. }
  489. }
  490. var index = this.$invalidFields.index($field);
  491. if (counter[this.STATUS_VALID] == numValidators) {
  492. // Remove from the list of invalid fields
  493. if (index != -1) {
  494. this.$invalidFields.splice(index, 1);
  495. }
  496. this.$form.trigger($.Event('success.field.bv'), [field, $field]);
  497. }
  498. // If all validators are completed and there is at least one validator which doesn't pass
  499. else if (counter[this.STATUS_NOT_VALIDATED] == 0 && counter[this.STATUS_VALIDATING] == 0 && counter[this.STATUS_INVALID] > 0) {
  500. // Add to the list of invalid fields
  501. if (index == -1) {
  502. this.$invalidFields = this.$invalidFields.add($field);
  503. }
  504. this.$form.trigger($.Event('error.field.bv'), [field, $field]);
  505. }
  506. },
  507. // --- Public methods ---
  508. /**
  509. * Retrieve the field elements by given name
  510. *
  511. * @param {String} field The field name
  512. * @returns {null|jQuery[]}
  513. */
  514. getFieldElements: function(field) {
  515. if (!this._cacheFields[field]) {
  516. this._cacheFields[field] = this.options.fields[field].selector
  517. ? $(this.options.fields[field].selector)
  518. : this.$form.find('[name="' + field + '"]');
  519. }
  520. return this._cacheFields[field];
  521. },
  522. /**
  523. * Disable/enable submit buttons
  524. *
  525. * @param {Boolean} disabled Can be true or false
  526. * @returns {BootstrapValidator}
  527. */
  528. disableSubmitButtons: function(disabled) {
  529. if (!disabled) {
  530. this.$form.find(this.options.submitButtons).removeAttr('disabled');
  531. } else if (this.options.live != 'disabled') {
  532. // Don't disable if the live validating mode is disabled
  533. this.$form.find(this.options.submitButtons).attr('disabled', 'disabled');
  534. }
  535. return this;
  536. },
  537. /**
  538. * Validate the form
  539. *
  540. * @returns {BootstrapValidator}
  541. */
  542. validate: function() {
  543. if (!this.options.fields) {
  544. return this;
  545. }
  546. this.disableSubmitButtons(true);
  547. for (var field in this.options.fields) {
  548. this.validateField(field);
  549. }
  550. this._submit();
  551. return this;
  552. },
  553. /**
  554. * Validate given field
  555. *
  556. * @param {String} field The field name
  557. * @returns {BootstrapValidator}
  558. */
  559. validateField: function(field) {
  560. var fields = this.getFieldElements(field),
  561. type = fields.attr('type'),
  562. n = (('radio' == type) || ('checkbox' == type)) ? 1 : fields.length;
  563. for (var i = 0; i < n; i++) {
  564. this.validateFieldElement($(fields[i]));
  565. }
  566. return this;
  567. },
  568. /**
  569. * Validate field element
  570. *
  571. * @param {jQuery} $field The field element
  572. * @returns {BootstrapValidator}
  573. */
  574. validateFieldElement: function($field) {
  575. var that = this,
  576. field = $field.attr('data-bv-field'),
  577. fields = this.getFieldElements(field),
  578. type = $field.attr('type'),
  579. updateAll = (fields && fields.length == 1) || ('radio' == type) || ('checkbox' == type),
  580. validators = this.options.fields[field].validators,
  581. validatorName,
  582. validateResult;
  583. if (!this.options.fields[field]['enabled'] || this._isExcluded($field)) {
  584. return this;
  585. }
  586. for (validatorName in validators) {
  587. if ($field.data('bv.dfs.' + validatorName)) {
  588. $field.data('bv.dfs.' + validatorName).reject();
  589. }
  590. // Don't validate field if it is already done
  591. var result = $field.data('bv.result.' + validatorName);
  592. if (result == this.STATUS_VALID || result == this.STATUS_INVALID) {
  593. this._onValidateFieldCompleted($field);
  594. continue;
  595. }
  596. $field.data('bv.result.' + validatorName, this.STATUS_VALIDATING);
  597. validateResult = $.fn.bootstrapValidator.validators[validatorName].validate(this, $field, validators[validatorName]);
  598. if ('object' == typeof validateResult) {
  599. updateAll ? this.updateStatus(field, this.STATUS_VALIDATING, validatorName)
  600. : this.updateElementStatus($field, this.STATUS_VALIDATING, validatorName);
  601. $field.data('bv.dfs.' + validatorName, validateResult);
  602. validateResult.done(function($f, v, isValid) {
  603. // v is validator name
  604. $f.removeData('bv.dfs.' + v);
  605. updateAll ? that.updateStatus($f.attr('data-bv-field'), isValid ? that.STATUS_VALID : that.STATUS_INVALID, v)
  606. : that.updateElementStatus($f, isValid ? that.STATUS_VALID : that.STATUS_INVALID, v);
  607. if (isValid && that._submitIfValid == true) {
  608. // If a remote validator returns true and the form is ready to submit, then do it
  609. that._submit();
  610. }
  611. });
  612. } else if ('boolean' == typeof validateResult) {
  613. updateAll ? this.updateStatus(field, validateResult ? this.STATUS_VALID : this.STATUS_INVALID, validatorName)
  614. : this.updateElementStatus($field, validateResult ? this.STATUS_VALID : this.STATUS_INVALID, validatorName);
  615. }
  616. }
  617. return this;
  618. },
  619. /**
  620. * Update all validating results of elements which have the same field name
  621. *
  622. * @param {String} field The field name
  623. * @param {String} status The status. Can be 'NOT_VALIDATED', 'VALIDATING', 'INVALID' or 'VALID'
  624. * @param {String} [validatorName] The validator name. If null, the method updates validity result for all validators
  625. * @returns {BootstrapValidator}
  626. */
  627. updateStatus: function(field, status, validatorName) {
  628. var fields = this.getFieldElements(field),
  629. type = fields.attr('type'),
  630. n = (('radio' == type) || ('checkbox' == type)) ? 1 : fields.length;
  631. for (var i = 0; i < n; i++) {
  632. this.updateElementStatus($(fields[i]), status, validatorName);
  633. }
  634. return this;
  635. },
  636. /**
  637. * Update validating result of given element
  638. *
  639. * @param {jQuery} $field The field element
  640. * @param {String} status The status. Can be 'NOT_VALIDATED', 'VALIDATING', 'INVALID' or 'VALID'
  641. * @param {String} [validatorName] The validator name. If null, the method updates validity result for all validators
  642. * @returns {BootstrapValidator}
  643. */
  644. updateElementStatus: function($field, status, validatorName) {
  645. var that = this,
  646. field = $field.attr('data-bv-field'),
  647. $parent = $field.parents('.form-group'),
  648. $message = $field.data('bv.messages'),
  649. $allErrors = $message.find('.help-block[data-bv-validator][data-bv-for="' + field + '"]'),
  650. $errors = validatorName ? $allErrors.filter('[data-bv-validator="' + validatorName + '"]') : $allErrors,
  651. $icon = $parent.find('.form-control-feedback[data-bv-icon-for="' + field + '"]'),
  652. container = this.options.fields[field].container || this.options.container;
  653. // Update status
  654. if (validatorName) {
  655. $field.data('bv.result.' + validatorName, status);
  656. } else {
  657. for (var v in this.options.fields[field].validators) {
  658. $field.data('bv.result.' + v, status);
  659. }
  660. }
  661. // Determine the tab containing the element
  662. var $tabPane = $field.parents('.tab-pane'),
  663. tabId,
  664. $tab;
  665. if ($tabPane && (tabId = $tabPane.attr('id'))) {
  666. $tab = $('a[href="#' + tabId + '"][data-toggle="tab"]').parent();
  667. }
  668. // Show/hide error elements and feedback icons
  669. $errors.attr('data-bv-result', status);
  670. switch (status) {
  671. case this.STATUS_VALIDATING:
  672. this.disableSubmitButtons(true);
  673. $parent.removeClass('has-success').removeClass('has-error');
  674. if ($icon) {
  675. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).addClass(this.options.feedbackIcons.validating).show();
  676. }
  677. if ($tab) {
  678. $tab.removeClass('bv-tab-success').removeClass('bv-tab-error');
  679. }
  680. switch (true) {
  681. case ($icon && 'tooltip' == container):
  682. $icon.css('cursor', '').tooltip('destroy');
  683. break;
  684. case ($icon && 'popover' == container):
  685. $icon.css('cursor', '').popover('destroy');
  686. break;
  687. default:
  688. $errors.hide();
  689. break;
  690. }
  691. break;
  692. case this.STATUS_INVALID:
  693. this.disableSubmitButtons(true);
  694. $parent.removeClass('has-success').addClass('has-error');
  695. if ($icon) {
  696. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.validating).addClass(this.options.feedbackIcons.invalid).show();
  697. }
  698. if ($tab) {
  699. $tab.removeClass('bv-tab-success').addClass('bv-tab-error');
  700. }
  701. switch (true) {
  702. // Only show the first error message if it is placed inside a tooltip or popover
  703. case ($icon && 'tooltip' == container):
  704. $icon.css('cursor', 'pointer').tooltip('destroy').tooltip({
  705. html: true,
  706. placement: 'top',
  707. title: $allErrors.filter('[data-bv-result="' + that.STATUS_INVALID + '"]').eq(0).html()
  708. });
  709. break;
  710. case ($icon && 'popover' == container):
  711. $icon.css('cursor', 'pointer').popover('destroy').popover({
  712. content: $allErrors.filter('[data-bv-result="' + that.STATUS_INVALID + '"]').eq(0).html(),
  713. html: true,
  714. placement: 'top',
  715. trigger: 'hover click'
  716. });
  717. break;
  718. default:
  719. $errors.show();
  720. break;
  721. }
  722. break;
  723. case this.STATUS_VALID:
  724. // If the field is valid (passes all validators)
  725. var validField = $allErrors.filter(function() {
  726. var v = $(this).attr('data-bv-validator');
  727. return $field.data('bv.result.' + v) != that.STATUS_VALID;
  728. }).length == 0;
  729. this.disableSubmitButtons(!validField);
  730. if ($icon) {
  731. $icon
  732. .removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).removeClass(this.options.feedbackIcons.valid)
  733. .addClass(validField ? this.options.feedbackIcons.valid : this.options.feedbackIcons.invalid)
  734. .show();
  735. }
  736. // Check if all elements in given container are valid
  737. var isValidContainer = function($container) {
  738. var map = {};
  739. $container.find('[data-bv-field]').each(function() {
  740. var field = $(this).attr('data-bv-field');
  741. if (!map[field]) {
  742. map[field] = $(this).data('bv.messages');
  743. }
  744. });
  745. for (var field in map) {
  746. if (map[field]
  747. .find('.help-block[data-bv-validator][data-bv-for="' + field + '"]')
  748. .filter(function() {
  749. var display = $(this).css('display'), v = $(this).attr('data-bv-validator');
  750. return ('block' == display) || ($field.data('bv.result.' + v) && $field.data('bv.result.' + v) != that.STATUS_VALID);
  751. })
  752. .length != 0)
  753. {
  754. // The field is not valid
  755. return false;
  756. }
  757. }
  758. return true;
  759. };
  760. $parent.removeClass('has-error has-success').addClass(isValidContainer($parent) ? 'has-success' : 'has-error');
  761. if ($tab) {
  762. $tab.removeClass('bv-tab-success').removeClass('bv-tab-error').addClass(isValidContainer($tabPane) ? 'bv-tab-success' : 'bv-tab-error');
  763. }
  764. switch (true) {
  765. // Only show the first error message if it is placed inside a tooltip or popover
  766. case ($icon && 'tooltip' == container):
  767. validField ? $icon.css('cursor', '').tooltip('destroy')
  768. : $icon.css('cursor', 'pointer').tooltip('destroy').tooltip({
  769. html: true,
  770. placement: 'top',
  771. title: $allErrors.filter('[data-bv-result="' + that.STATUS_INVALID + '"]').eq(0).html()
  772. });
  773. break;
  774. case ($icon && 'popover' == container):
  775. validField ? $icon.css('cursor', '').popover('destroy')
  776. : $icon.css('cursor', 'pointer').popover('destroy').popover({
  777. content: $allErrors.filter('[data-bv-result="' + that.STATUS_INVALID + '"]').eq(0).html(),
  778. html: true,
  779. placement: 'top',
  780. trigger: 'hover click'
  781. });
  782. break;
  783. default:
  784. $errors.hide();
  785. break;
  786. }
  787. break;
  788. case this.STATUS_NOT_VALIDATED:
  789. default:
  790. this.disableSubmitButtons(false);
  791. $parent.removeClass('has-success').removeClass('has-error');
  792. if ($icon) {
  793. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).hide();
  794. }
  795. if ($tab) {
  796. $tab.removeClass('bv-tab-success').removeClass('bv-tab-error');
  797. }
  798. switch (true) {
  799. case ($icon && 'tooltip' == container):
  800. $icon.css('cursor', '').tooltip('destroy');
  801. break;
  802. case ($icon && 'popover' == container):
  803. $icon.css('cursor', '').popover('destroy');
  804. break;
  805. default:
  806. $errors.hide();
  807. break;
  808. }
  809. break;
  810. }
  811. this._onValidateFieldCompleted($field);
  812. return this;
  813. },
  814. /**
  815. * Check the form validity
  816. *
  817. * @returns {Boolean}
  818. */
  819. isValid: function() {
  820. var fields, field, $field,
  821. type, status, validatorName,
  822. n, i;
  823. for (field in this.options.fields) {
  824. if (this.options.fields[field] == null || !this.options.fields[field]['enabled']) {
  825. continue;
  826. }
  827. fields = this.getFieldElements(field);
  828. type = fields.attr('type');
  829. n = (('radio' == type) || ('checkbox' == type)) ? 1 : fields.length;
  830. for (i = 0; i < n; i++) {
  831. $field = $(fields[i]);
  832. if (this._isExcluded($field)) {
  833. continue;
  834. }
  835. for (validatorName in this.options.fields[field].validators) {
  836. status = $field.data('bv.result.' + validatorName);
  837. if (status != this.STATUS_VALID) {
  838. return false;
  839. }
  840. }
  841. }
  842. }
  843. return true;
  844. },
  845. /**
  846. * Submit the form using default submission.
  847. * It also does not perform any validations when submitting the form
  848. *
  849. * It might be used when you want to submit the form right inside the submitHandler()
  850. */
  851. defaultSubmit: function() {
  852. this.$form.off('submit.bv').submit();
  853. },
  854. // Useful APIs which aren't used internally
  855. /**
  856. * Get the list of invalid fields
  857. *
  858. * @returns {jQuery[]}
  859. */
  860. getInvalidFields: function() {
  861. return this.$invalidFields;
  862. },
  863. /**
  864. * Add new field element
  865. *
  866. * @param {jQuery} $field The field element
  867. * @param {Object} options The field options
  868. * @returns {BootstrapValidator}
  869. */
  870. addFieldElement: function($field, options) {
  871. var field = $field.attr('name') || $field.attr('data-bv-field'),
  872. type = $field.attr('type'),
  873. isNewField = !this._cacheFields[field];
  874. // Update cache
  875. if (!isNewField && this._cacheFields[field].index($field) == -1) {
  876. this._cacheFields[field] = this._cacheFields[field].add($field);
  877. }
  878. if ('checkbox' == type || 'radio' == type || isNewField) {
  879. this._initField(field);
  880. } else {
  881. this._initFieldElement($field);
  882. }
  883. return this;
  884. },
  885. /**
  886. * Remove given field element
  887. *
  888. * @param {jQuery} $field The field element
  889. * @returns {BootstrapValidator}
  890. */
  891. removeFieldElement: function($field) {
  892. var field = $field.attr('name') || $field.attr('data-bv-field'),
  893. type = $field.attr('type'),
  894. index = this._cacheFields[field].index($field);
  895. (index == -1) ? (delete this._cacheFields[field]) : this._cacheFields[field].splice(index, 1);
  896. // Remove from the list of invalid fields
  897. index = this.$invalidFields.index($field);
  898. if (index != -1) {
  899. this.$invalidFields.splice(index, 1);
  900. }
  901. if ('checkbox' == type || 'radio' == type) {
  902. this._initField(field);
  903. }
  904. return this;
  905. },
  906. /**
  907. * Reset the form
  908. *
  909. * @param {Boolean} resetFormData Reset current form data
  910. * @return {BootstrapValidator}
  911. */
  912. resetForm: function(resetFormData) {
  913. var field, fields, total, type, validator;
  914. for (field in this.options.fields) {
  915. fields = this.getFieldElements(field);
  916. total = fields.length;
  917. for (var i = 0; i < total; i++) {
  918. for (validator in this.options.fields[field].validators) {
  919. $(fields[i]).removeData('bv.dfs.' + validator);
  920. }
  921. }
  922. // Mark field as not validated yet
  923. this.updateStatus(field, this.STATUS_NOT_VALIDATED);
  924. if (resetFormData) {
  925. type = fields.attr('type');
  926. ('radio' == type || 'checkbox' == type) ? fields.removeAttr('checked').removeAttr('selected') : fields.val('');
  927. }
  928. }
  929. this.$invalidFields = $([]);
  930. this.$submitButton = null;
  931. // Enable submit buttons
  932. this.disableSubmitButtons(false);
  933. return this;
  934. },
  935. /**
  936. * Enable/Disable all validators to given field
  937. *
  938. * @param {String} field The field name
  939. * @param {Boolean} enabled Enable/Disable field validators
  940. * @returns {BootstrapValidator}
  941. */
  942. enableFieldValidators: function(field, enabled) {
  943. this.options.fields[field]['enabled'] = enabled;
  944. this.updateStatus(field, this.STATUS_NOT_VALIDATED);
  945. return this;
  946. }
  947. };
  948. // Plugin definition
  949. $.fn.bootstrapValidator = function(option) {
  950. var params = arguments;
  951. return this.each(function() {
  952. var $this = $(this),
  953. data = $this.data('bootstrapValidator'),
  954. options = 'object' == typeof option && option;
  955. if (!data) {
  956. data = new BootstrapValidator(this, options);
  957. $this.data('bootstrapValidator', data);
  958. }
  959. // Allow to call plugin method
  960. if ('string' == typeof option) {
  961. data[option].apply(data, Array.prototype.slice.call(params, 1));
  962. }
  963. });
  964. };
  965. // Available validators
  966. $.fn.bootstrapValidator.validators = {};
  967. $.fn.bootstrapValidator.Constructor = BootstrapValidator;
  968. // Helper methods, which can be used in validator class
  969. $.fn.bootstrapValidator.helpers = {
  970. /**
  971. * Validate a date
  972. *
  973. * @param {Number} year The full year in 4 digits
  974. * @param {Number} month The month number
  975. * @param {Number} day The day number
  976. * @param {Boolean} [notInFuture] If true, the date must not be in the future
  977. * @returns {Boolean}
  978. */
  979. date: function(year, month, day, notInFuture) {
  980. if (year < 1000 || year > 9999 || month == 0 || month > 12) {
  981. return false;
  982. }
  983. var numDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  984. // Update the number of days in Feb of leap year
  985. if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
  986. numDays[1] = 29;
  987. }
  988. // Check the day
  989. if (day < 0 || day > numDays[month - 1]) {
  990. return false;
  991. }
  992. if (notInFuture === true) {
  993. var currentDate = new Date(),
  994. currentYear = currentDate.getFullYear(),
  995. currentMonth = currentDate.getMonth(),
  996. currentDay = currentDate.getDate();
  997. return (year < currentYear
  998. || (year == currentYear && month - 1 < currentMonth)
  999. || (year == currentYear && month - 1 == currentMonth && day < currentDay));
  1000. }
  1001. return true;
  1002. },
  1003. /**
  1004. * Implement Luhn validation algorithm
  1005. * Credit to https://gist.github.com/ShirtlessKirk/2134376
  1006. *
  1007. * @see http://en.wikipedia.org/wiki/Luhn
  1008. * @param {String} value
  1009. * @returns {Boolean}
  1010. */
  1011. luhn: function(value) {
  1012. var length = value.length,
  1013. mul = 0,
  1014. prodArr = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]],
  1015. sum = 0;
  1016. while (length--) {
  1017. sum += prodArr[mul][parseInt(value.charAt(length), 10)];
  1018. mul ^= 1;
  1019. }
  1020. return (sum % 10 === 0 && sum > 0);
  1021. },
  1022. /**
  1023. * Implement modulus 11, 10 (ISO 7064) algorithm
  1024. *
  1025. * @param {String} value
  1026. * @returns {Boolean}
  1027. */
  1028. mod_11_10: function(value) {
  1029. var check = 5,
  1030. length = value.length;
  1031. for (var i = 0; i < length; i++) {
  1032. check = (((check || 10) * 2) % 11 + parseInt(value.charAt(i), 10)) % 10;
  1033. }
  1034. return (check == 1);
  1035. },
  1036. /**
  1037. * Implements Mod 37, 36 (ISO 7064) algorithm
  1038. * Usages:
  1039. * mod_37_36('A12425GABC1234002M')
  1040. * mod_37_36('002006673085', '0123456789')
  1041. *
  1042. * @param {String} value
  1043. * @param {String} alphabet
  1044. * @returns {Boolean}
  1045. */
  1046. mod_37_36: function(value, alphabet) {
  1047. alphabet = alphabet || '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  1048. var modulus = alphabet.length,
  1049. length = value.length,
  1050. check = Math.floor(modulus / 2);
  1051. for (var i = 0; i < length; i++) {
  1052. check = (((check || modulus) * 2) % (modulus + 1) + alphabet.indexOf(value.charAt(i))) % modulus;
  1053. }
  1054. return (check == 1);
  1055. }
  1056. };
  1057. }(window.jQuery));