bootstrapValidator.js 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952
  1. /**
  2. * BootstrapValidator (http://bootstrapvalidator.com)
  3. * The best jQuery plugin to validate form fields. Designed to use with Bootstrap 3
  4. *
  5. * @author https://twitter.com/nghuuphuoc
  6. * @copyright (c) 2013 - 2014 Nguyen Huu Phuoc
  7. * @license MIT
  8. */
  9. if (typeof jQuery === 'undefined') {
  10. throw new Error('BootstrapValidator\'s JavaScript requires jQuery');
  11. }
  12. (function($) {
  13. var BootstrapValidator = function(form, options) {
  14. this.$form = $(form);
  15. this.options = $.extend({}, $.fn.bootstrapValidator.DEFAULT_OPTIONS, options);
  16. this.$invalidFields = $([]); // Array of invalid fields
  17. this.$submitButton = null; // The submit button which is clicked to submit form
  18. this.$hiddenButton = null;
  19. // Validating status
  20. this.STATUS_NOT_VALIDATED = 'NOT_VALIDATED';
  21. this.STATUS_VALIDATING = 'VALIDATING';
  22. this.STATUS_INVALID = 'INVALID';
  23. this.STATUS_VALID = 'VALID';
  24. // Determine the event that is fired when user change the field value
  25. // Most modern browsers supports input event except IE 7, 8.
  26. // IE 9 supports input event but the event is still not fired if I press the backspace key.
  27. // Get IE version
  28. // https://gist.github.com/padolsey/527683/#comment-7595
  29. var ieVersion = (function() {
  30. var v = 3, div = document.createElement('div'), a = div.all || [];
  31. while (div.innerHTML = '<!--[if gt IE '+(++v)+']><br><![endif]-->', a[0]) {}
  32. return v > 4 ? v : !v;
  33. }());
  34. var el = document.createElement('div');
  35. this._changeEvent = (ieVersion === 9 || !('oninput' in el)) ? 'keyup' : 'input';
  36. // The flag to indicate that the form is ready to submit when a remote/callback validator returns
  37. this._submitIfValid = null;
  38. // Field elements
  39. this._cacheFields = {};
  40. this._init();
  41. };
  42. BootstrapValidator.prototype = {
  43. constructor: BootstrapValidator,
  44. /**
  45. * Init form
  46. */
  47. _init: function() {
  48. var that = this,
  49. options = {
  50. container: this.$form.attr('data-bv-container'),
  51. events: {
  52. formInit: this.$form.attr('data-bv-events-form-init'),
  53. formError: this.$form.attr('data-bv-events-form-error'),
  54. formSuccess: this.$form.attr('data-bv-events-form-success'),
  55. fieldAdded: this.$form.attr('data-bv-events-field-added'),
  56. fieldRemoved: this.$form.attr('data-bv-events-field-removed'),
  57. fieldInit: this.$form.attr('data-bv-events-field-init'),
  58. fieldError: this.$form.attr('data-bv-events-field-error'),
  59. fieldSuccess: this.$form.attr('data-bv-events-field-success'),
  60. fieldStatus: this.$form.attr('data-bv-events-field-status'),
  61. validatorError: this.$form.attr('data-bv-events-validator-error'),
  62. validatorSuccess: this.$form.attr('data-bv-events-validator-success')
  63. },
  64. excluded: this.$form.attr('data-bv-excluded'),
  65. feedbackIcons: {
  66. valid: this.$form.attr('data-bv-feedbackicons-valid'),
  67. invalid: this.$form.attr('data-bv-feedbackicons-invalid'),
  68. validating: this.$form.attr('data-bv-feedbackicons-validating')
  69. },
  70. group: this.$form.attr('data-bv-group'),
  71. live: this.$form.attr('data-bv-live'),
  72. message: this.$form.attr('data-bv-message'),
  73. onError: this.$form.attr('data-bv-onerror'),
  74. onSuccess: this.$form.attr('data-bv-onsuccess'),
  75. submitButtons: this.$form.attr('data-bv-submitbuttons'),
  76. threshold: this.$form.attr('data-bv-threshold'),
  77. trigger: this.$form.attr('data-bv-trigger'),
  78. verbose: this.$form.attr('data-bv-verbose'),
  79. fields: {}
  80. };
  81. this.$form
  82. // Disable client side validation in HTML 5
  83. .attr('novalidate', 'novalidate')
  84. .addClass(this.options.elementClass)
  85. // Disable the default submission first
  86. .on('submit.bv', function(e) {
  87. e.preventDefault();
  88. that.validate();
  89. })
  90. .on('click.bv', this.options.submitButtons, function() {
  91. that.$submitButton = $(this);
  92. // The user just click the submit button
  93. that._submitIfValid = true;
  94. })
  95. // Find all fields which have either "name" or "data-bv-field" attribute
  96. .find('[name], [data-bv-field]')
  97. .each(function() {
  98. var $field = $(this),
  99. field = $field.attr('name') || $field.attr('data-bv-field'),
  100. opts = that._parseOptions($field);
  101. if (opts) {
  102. $field.attr('data-bv-field', field);
  103. options.fields[field] = $.extend({}, opts, options.fields[field]);
  104. }
  105. });
  106. this.options = $.extend(true, this.options, options);
  107. // When pressing Enter on any field in the form, the first submit button will do its job.
  108. // The form then will be submitted.
  109. // I create a first hidden submit button
  110. this.$hiddenButton = $('<button/>')
  111. .attr('type', 'submit')
  112. .prependTo(this.$form)
  113. .addClass('bv-hidden-submit')
  114. .css({ display: 'none', width: 0, height: 0 });
  115. this.$form
  116. .on('click.bv', '[type="submit"]', function(e) {
  117. // #746: Check if the button click handler returns false
  118. if (!e.isDefaultPrevented()) {
  119. var $target = $(e.target),
  120. // The button might contain HTML tag
  121. $button = $target.is('[type="submit"]') ? $target.eq(0) : $target.parent('[type="submit"]').eq(0);
  122. // Don't perform validation when clicking on the submit button/input
  123. // which aren't defined by the 'submitButtons' option
  124. if (that.options.submitButtons && !$button.is(that.options.submitButtons) && !$button.is(that.$hiddenButton)) {
  125. that.$form.off('submit.bv').submit();
  126. }
  127. }
  128. });
  129. for (var field in this.options.fields) {
  130. this._initField(field);
  131. }
  132. this.$form.trigger($.Event(this.options.events.formInit), {
  133. bv: this,
  134. options: this.options
  135. });
  136. // Prepare the events
  137. if (this.options.onSuccess) {
  138. this.$form.on(this.options.events.formSuccess, function(e) {
  139. $.fn.bootstrapValidator.helpers.call(that.options.onSuccess, [e]);
  140. });
  141. }
  142. if (this.options.onError) {
  143. this.$form.on(this.options.events.formError, function(e) {
  144. $.fn.bootstrapValidator.helpers.call(that.options.onError, [e]);
  145. });
  146. }
  147. },
  148. /**
  149. * Parse the validator options from HTML attributes
  150. *
  151. * @param {jQuery} $field The field element
  152. * @returns {Object}
  153. */
  154. _parseOptions: function($field) {
  155. var field = $field.attr('name') || $field.attr('data-bv-field'),
  156. validators = {},
  157. validator,
  158. v, // Validator name
  159. enabled,
  160. optionName,
  161. optionValue,
  162. html5AttrName,
  163. html5AttrMap;
  164. for (v in $.fn.bootstrapValidator.validators) {
  165. validator = $.fn.bootstrapValidator.validators[v];
  166. enabled = $field.attr('data-bv-' + v.toLowerCase()) + '';
  167. html5AttrMap = ('function' === typeof validator.enableByHtml5) ? validator.enableByHtml5($field) : null;
  168. if ((html5AttrMap && enabled !== 'false')
  169. || (html5AttrMap !== true && ('' === enabled || 'true' === enabled)))
  170. {
  171. // Try to parse the options via attributes
  172. validator.html5Attributes = $.extend({}, { message: 'message', onerror: 'onError', onsuccess: 'onSuccess' }, validator.html5Attributes);
  173. validators[v] = $.extend({}, html5AttrMap === true ? {} : html5AttrMap, 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. container: $field.attr('data-bv-container'),
  190. excluded: $field.attr('data-bv-excluded'),
  191. feedbackIcons: $field.attr('data-bv-feedbackicons'),
  192. group: $field.attr('data-bv-group'),
  193. message: $field.attr('data-bv-message'),
  194. onError: $field.attr('data-bv-onerror'),
  195. onStatus: $field.attr('data-bv-onstatus'),
  196. onSuccess: $field.attr('data-bv-onsuccess'),
  197. selector: $field.attr('data-bv-selector'),
  198. threshold: $field.attr('data-bv-threshold'),
  199. trigger: $field.attr('data-bv-trigger'),
  200. verbose: $field.attr('data-bv-verbose'),
  201. validators: validators
  202. },
  203. emptyOptions = $.isEmptyObject(opts), // Check if the field options are set using HTML attributes
  204. emptyValidators = $.isEmptyObject(validators); // Check if the field validators are set using HTML attributes
  205. if (!emptyValidators || (!emptyOptions && this.options.fields && this.options.fields[field])) {
  206. opts.validators = validators;
  207. return opts;
  208. } else {
  209. return null;
  210. }
  211. },
  212. /**
  213. * Init field
  214. *
  215. * @param {String|jQuery} field The field name or field element
  216. */
  217. _initField: function(field) {
  218. var fields = $([]);
  219. switch (typeof field) {
  220. case 'object':
  221. fields = field;
  222. field = field.attr('data-bv-field');
  223. break;
  224. case 'string':
  225. fields = this.getFieldElements(field);
  226. fields.attr('data-bv-field', field);
  227. break;
  228. default:
  229. break;
  230. }
  231. // We don't need to validate non-existing fields
  232. if (fields.length === 0) {
  233. return;
  234. }
  235. if (this.options.fields[field] === null || this.options.fields[field].validators === null) {
  236. return;
  237. }
  238. var validatorName;
  239. for (validatorName in this.options.fields[field].validators) {
  240. if (!$.fn.bootstrapValidator.validators[validatorName]) {
  241. delete this.options.fields[field].validators[validatorName];
  242. }
  243. }
  244. if (this.options.fields[field].enabled === null) {
  245. this.options.fields[field].enabled = true;
  246. }
  247. var that = this,
  248. total = fields.length,
  249. type = fields.attr('type'),
  250. updateAll = (total === 1) || ('radio' === type) || ('checkbox' === type),
  251. event = ('radio' === type || 'checkbox' === type || 'file' === type || 'SELECT' === fields.eq(0).get(0).tagName) ? 'change' : this._changeEvent,
  252. trigger = (this.options.fields[field].trigger || this.options.trigger || event).split(' '),
  253. events = $.map(trigger, function(item) {
  254. return item + '.update.bv';
  255. }).join(' ');
  256. for (var i = 0; i < total; i++) {
  257. var $field = fields.eq(i),
  258. group = this.options.fields[field].group || this.options.group,
  259. $parent = $field.parents(group),
  260. // Allow user to indicate where the error messages are shown
  261. container = ('function' === typeof (this.options.fields[field].container || this.options.container)) ? (this.options.fields[field].container || this.options.container).call(this, $field, this) : (this.options.fields[field].container || this.options.container),
  262. $message = (container && container !== 'tooltip' && container !== 'popover') ? $(container) : this._getMessageContainer($field, group);
  263. if (container && container !== 'tooltip' && container !== 'popover') {
  264. $message.addClass('has-error');
  265. }
  266. // Remove all error messages and feedback icons
  267. $message.find('.help-block[data-bv-validator][data-bv-for="' + field + '"]').remove();
  268. $parent.find('i[data-bv-icon-for="' + field + '"]').remove();
  269. // Whenever the user change the field value, mark it as not validated yet
  270. $field.off(events).on(events, function() {
  271. that.updateStatus($(this), that.STATUS_NOT_VALIDATED);
  272. });
  273. // Create help block elements for showing the error messages
  274. $field.data('bv.messages', $message);
  275. for (validatorName in this.options.fields[field].validators) {
  276. $field.data('bv.result.' + validatorName, this.STATUS_NOT_VALIDATED);
  277. if (!updateAll || i === total - 1) {
  278. $('<small/>')
  279. .css('display', 'none')
  280. .addClass('help-block')
  281. .attr('data-bv-validator', validatorName)
  282. .attr('data-bv-for', field)
  283. .attr('data-bv-result', this.STATUS_NOT_VALIDATED)
  284. .html(this._getMessage(field, validatorName))
  285. .appendTo($message);
  286. }
  287. // Init the validator
  288. if ('function' === typeof $.fn.bootstrapValidator.validators[validatorName].init) {
  289. $.fn.bootstrapValidator.validators[validatorName].init(this, $field, this.options.fields[field].validators[validatorName]);
  290. }
  291. }
  292. // Prepare the feedback icons
  293. // Available from Bootstrap 3.1 (http://getbootstrap.com/css/#forms-control-validation)
  294. if (this.options.fields[field].feedbackIcons !== false && this.options.fields[field].feedbackIcons !== 'false'
  295. && this.options.feedbackIcons
  296. && this.options.feedbackIcons.validating && this.options.feedbackIcons.invalid && this.options.feedbackIcons.valid
  297. && (!updateAll || i === total - 1))
  298. {
  299. // $parent.removeClass('has-success').removeClass('has-error').addClass('has-feedback');
  300. // Keep error messages which are populated from back-end
  301. $parent.addClass('has-feedback');
  302. var $icon = $('<i/>')
  303. .css('display', 'none')
  304. .addClass('form-control-feedback')
  305. .attr('data-bv-icon-for', field)
  306. .insertAfter($field);
  307. // Place it after the container of checkbox/radio
  308. // so when clicking the icon, it doesn't effect to the checkbox/radio element
  309. if ('checkbox' === type || 'radio' === type) {
  310. var $fieldParent = $field.parent();
  311. if ($fieldParent.hasClass(type)) {
  312. $icon.insertAfter($fieldParent);
  313. } else if ($fieldParent.parent().hasClass(type)) {
  314. $icon.insertAfter($fieldParent.parent());
  315. }
  316. }
  317. // The feedback icon does not render correctly if there is no label
  318. // https://github.com/twbs/bootstrap/issues/12873
  319. if ($parent.find('label').length === 0) {
  320. $icon.addClass('bv-no-label');
  321. }
  322. // Fix feedback icons in input-group
  323. if ($parent.find('.input-group').length !== 0) {
  324. $icon.addClass('bv-icon-input-group')
  325. .insertAfter($parent.find('.input-group').eq(0));
  326. }
  327. if (container) {
  328. $field
  329. // Show tooltip/popover message when field gets focus
  330. .off('focus.bv')
  331. .on('focus.bv', function() {
  332. switch (container) {
  333. case 'tooltip':
  334. $icon.tooltip('show');
  335. break;
  336. case 'popover':
  337. $icon.popover('show');
  338. break;
  339. default:
  340. break;
  341. }
  342. })
  343. // and hide them when losing focus
  344. .off('blur.bv')
  345. .on('blur.bv', function() {
  346. switch (container) {
  347. case 'tooltip':
  348. $icon.tooltip('hide');
  349. break;
  350. case 'popover':
  351. $icon.popover('hide');
  352. break;
  353. default:
  354. break;
  355. }
  356. });
  357. }
  358. }
  359. }
  360. // Prepare the events
  361. fields
  362. .on(this.options.events.fieldSuccess, function(e, data) {
  363. var onSuccess = that.getOptions(data.field, null, 'onSuccess');
  364. if (onSuccess) {
  365. $.fn.bootstrapValidator.helpers.call(onSuccess, [e, data]);
  366. }
  367. })
  368. .on(this.options.events.fieldError, function(e, data) {
  369. var onError = that.getOptions(data.field, null, 'onError');
  370. if (onError) {
  371. $.fn.bootstrapValidator.helpers.call(onError, [e, data]);
  372. }
  373. })
  374. .on(this.options.events.fieldStatus, function(e, data) {
  375. var onStatus = that.getOptions(data.field, null, 'onStatus');
  376. if (onStatus) {
  377. $.fn.bootstrapValidator.helpers.call(onStatus, [e, data]);
  378. }
  379. })
  380. .on(this.options.events.validatorError, function(e, data) {
  381. var onError = that.getOptions(data.field, data.validator, 'onError');
  382. if (onError) {
  383. $.fn.bootstrapValidator.helpers.call(onError, [e, data]);
  384. }
  385. })
  386. .on(this.options.events.validatorSuccess, function(e, data) {
  387. var onSuccess = that.getOptions(data.field, data.validator, 'onSuccess');
  388. if (onSuccess) {
  389. $.fn.bootstrapValidator.helpers.call(onSuccess, [e, data]);
  390. }
  391. });
  392. // Set live mode
  393. events = $.map(trigger, function(item) {
  394. return item + '.live.bv';
  395. }).join(' ');
  396. switch (this.options.live) {
  397. case 'submitted':
  398. break;
  399. case 'disabled':
  400. fields.off(events);
  401. break;
  402. case 'enabled':
  403. /* falls through */
  404. default:
  405. fields.off(events).on(events, function() {
  406. if (that._exceedThreshold($(this))) {
  407. that.validateField($(this));
  408. }
  409. });
  410. break;
  411. }
  412. fields.trigger($.Event(this.options.events.fieldInit), {
  413. bv: this,
  414. field: field,
  415. element: fields
  416. });
  417. },
  418. /**
  419. * Get the error message for given field and validator
  420. *
  421. * @param {String} field The field name
  422. * @param {String} validatorName The validator name
  423. * @returns {String}
  424. */
  425. _getMessage: function(field, validatorName) {
  426. if (!this.options.fields[field] || !$.fn.bootstrapValidator.validators[validatorName]
  427. || !this.options.fields[field].validators || !this.options.fields[field].validators[validatorName])
  428. {
  429. return '';
  430. }
  431. var options = this.options.fields[field].validators[validatorName];
  432. switch (true) {
  433. case (!!options.message):
  434. return options.message;
  435. case (!!this.options.fields[field].message):
  436. return this.options.fields[field].message;
  437. case (!!$.fn.bootstrapValidator.i18n[validatorName]):
  438. return $.fn.bootstrapValidator.i18n[validatorName]['default'];
  439. default:
  440. return this.options.message;
  441. }
  442. },
  443. /**
  444. * Get the element to place the error messages
  445. *
  446. * @param {jQuery} $field The field element
  447. * @param {String} group
  448. * @returns {jQuery}
  449. */
  450. _getMessageContainer: function($field, group) {
  451. var $parent = $field.parent();
  452. if ($parent.is(group)) {
  453. return $parent;
  454. }
  455. var cssClasses = $parent.attr('class');
  456. if (!cssClasses) {
  457. return this._getMessageContainer($parent, group);
  458. }
  459. cssClasses = cssClasses.split(' ');
  460. var n = cssClasses.length;
  461. for (var i = 0; i < n; i++) {
  462. if (/^col-(xs|sm|md|lg)-\d+$/.test(cssClasses[i]) || /^col-(xs|sm|md|lg)-offset-\d+$/.test(cssClasses[i])) {
  463. return $parent;
  464. }
  465. }
  466. return this._getMessageContainer($parent, group);
  467. },
  468. /**
  469. * Called when all validations are completed
  470. */
  471. _submit: function() {
  472. var isValid = this.isValid(),
  473. eventType = isValid ? this.options.events.formSuccess : this.options.events.formError,
  474. e = $.Event(eventType);
  475. this.$form.trigger(e);
  476. // Call default handler
  477. // Check if whether the submit button is clicked
  478. if (this.$submitButton) {
  479. isValid ? this._onSuccess(e) : this._onError(e);
  480. }
  481. },
  482. /**
  483. * Check if the field is excluded.
  484. * Returning true means that the field will not be validated
  485. *
  486. * @param {jQuery} $field The field element
  487. * @returns {Boolean}
  488. */
  489. _isExcluded: function($field) {
  490. var excludedAttr = $field.attr('data-bv-excluded'),
  491. // I still need to check the 'name' attribute while initializing the field
  492. field = $field.attr('data-bv-field') || $field.attr('name');
  493. switch (true) {
  494. case (!!field && this.options.fields && this.options.fields[field] && (this.options.fields[field].excluded === 'true' || this.options.fields[field].excluded === true)):
  495. case (excludedAttr === 'true'):
  496. case (excludedAttr === ''):
  497. return true;
  498. case (!!field && this.options.fields && this.options.fields[field] && (this.options.fields[field].excluded === 'false' || this.options.fields[field].excluded === false)):
  499. case (excludedAttr === 'false'):
  500. return false;
  501. default:
  502. if (this.options.excluded) {
  503. // Convert to array first
  504. if ('string' === typeof this.options.excluded) {
  505. this.options.excluded = $.map(this.options.excluded.split(','), function(item) {
  506. // Trim the spaces
  507. return $.trim(item);
  508. });
  509. }
  510. var length = this.options.excluded.length;
  511. for (var i = 0; i < length; i++) {
  512. if (('string' === typeof this.options.excluded[i] && $field.is(this.options.excluded[i]))
  513. || ('function' === typeof this.options.excluded[i] && this.options.excluded[i].call(this, $field, this) === true))
  514. {
  515. return true;
  516. }
  517. }
  518. }
  519. return false;
  520. }
  521. },
  522. /**
  523. * Check if the number of characters of field value exceed the threshold or not
  524. *
  525. * @param {jQuery} $field The field element
  526. * @returns {Boolean}
  527. */
  528. _exceedThreshold: function($field) {
  529. var field = $field.attr('data-bv-field'),
  530. threshold = this.options.fields[field].threshold || this.options.threshold;
  531. if (!threshold) {
  532. return true;
  533. }
  534. var cannotType = $.inArray($field.attr('type'), ['button', 'checkbox', 'file', 'hidden', 'image', 'radio', 'reset', 'submit']) !== -1;
  535. return (cannotType || $field.val().length >= threshold);
  536. },
  537. // ---
  538. // Events
  539. // ---
  540. /**
  541. * The default handler of error.form.bv event.
  542. * It will be called when there is a invalid field
  543. *
  544. * @param {jQuery.Event} e The jQuery event object
  545. */
  546. _onError: function(e) {
  547. if (e.isDefaultPrevented()) {
  548. return;
  549. }
  550. if ('submitted' === this.options.live) {
  551. // Enable live mode
  552. this.options.live = 'enabled';
  553. var that = this;
  554. for (var field in this.options.fields) {
  555. (function(f) {
  556. var fields = that.getFieldElements(f);
  557. if (fields.length) {
  558. var type = $(fields[0]).attr('type'),
  559. event = ('radio' === type || 'checkbox' === type || 'file' === type || 'SELECT' === $(fields[0]).get(0).tagName) ? 'change' : that._changeEvent,
  560. trigger = that.options.fields[field].trigger || that.options.trigger || event,
  561. events = $.map(trigger.split(' '), function(item) {
  562. return item + '.live.bv';
  563. }).join(' ');
  564. fields.off(events).on(events, function() {
  565. if (that._exceedThreshold($(this))) {
  566. that.validateField($(this));
  567. }
  568. });
  569. }
  570. })(field);
  571. }
  572. }
  573. var $invalidField = this.$invalidFields.eq(0);
  574. if ($invalidField) {
  575. // Activate the tab containing the invalid field if exists
  576. var $tabPane = $invalidField.parents('.tab-pane'), tabId;
  577. if ($tabPane && (tabId = $tabPane.attr('id'))) {
  578. $('a[href="#' + tabId + '"][data-toggle="tab"]').tab('show');
  579. }
  580. // Focus to the first invalid field
  581. $invalidField.focus();
  582. }
  583. },
  584. /**
  585. * The default handler of success.form.bv event.
  586. * It will be called when all the fields are valid
  587. *
  588. * @param {jQuery.Event} e The jQuery event object
  589. */
  590. _onSuccess: function(e) {
  591. if (e.isDefaultPrevented()) {
  592. return;
  593. }
  594. // Submit the form
  595. this.disableSubmitButtons(true).defaultSubmit();
  596. },
  597. /**
  598. * Called after validating a field element
  599. *
  600. * @param {jQuery} $field The field element
  601. * @param {String} [validatorName] The validator name
  602. */
  603. _onFieldValidated: function($field, validatorName) {
  604. var field = $field.attr('data-bv-field'),
  605. validators = this.options.fields[field].validators,
  606. counter = {},
  607. numValidators = 0,
  608. data = {
  609. bv: this,
  610. field: field,
  611. element: $field,
  612. validator: validatorName,
  613. result: $field.data('bv.response.' + validatorName)
  614. };
  615. // Trigger an event after given validator completes
  616. if (validatorName) {
  617. switch ($field.data('bv.result.' + validatorName)) {
  618. case this.STATUS_INVALID:
  619. $field.trigger($.Event(this.options.events.validatorError), data);
  620. break;
  621. case this.STATUS_VALID:
  622. $field.trigger($.Event(this.options.events.validatorSuccess), data);
  623. break;
  624. default:
  625. break;
  626. }
  627. }
  628. counter[this.STATUS_NOT_VALIDATED] = 0;
  629. counter[this.STATUS_VALIDATING] = 0;
  630. counter[this.STATUS_INVALID] = 0;
  631. counter[this.STATUS_VALID] = 0;
  632. for (var v in validators) {
  633. if (validators[v].enabled === false) {
  634. continue;
  635. }
  636. numValidators++;
  637. var result = $field.data('bv.result.' + v);
  638. if (result) {
  639. counter[result]++;
  640. }
  641. }
  642. if (counter[this.STATUS_VALID] === numValidators) {
  643. // Remove from the list of invalid fields
  644. this.$invalidFields = this.$invalidFields.not($field);
  645. $field.trigger($.Event(this.options.events.fieldSuccess), data);
  646. }
  647. // If all validators are completed and there is at least one validator which doesn't pass
  648. else if (counter[this.STATUS_NOT_VALIDATED] === 0 && counter[this.STATUS_VALIDATING] === 0 && counter[this.STATUS_INVALID] > 0) {
  649. // Add to the list of invalid fields
  650. this.$invalidFields = this.$invalidFields.add($field);
  651. $field.trigger($.Event(this.options.events.fieldError), data);
  652. }
  653. },
  654. // ---
  655. // Public methods
  656. // ---
  657. /**
  658. * Retrieve the field elements by given name
  659. *
  660. * @param {String} field The field name
  661. * @returns {null|jQuery[]}
  662. */
  663. getFieldElements: function(field) {
  664. if (!this._cacheFields[field]) {
  665. this._cacheFields[field] = (this.options.fields[field] && this.options.fields[field].selector)
  666. ? $(this.options.fields[field].selector)
  667. : this.$form.find('[name="' + field + '"]');
  668. }
  669. return this._cacheFields[field];
  670. },
  671. /**
  672. * Get the field options
  673. *
  674. * @param {String|jQuery} [field] The field name or field element. If it is not set, the method returns the form options
  675. * @param {String} [validator] The name of validator. It null, the method returns form options
  676. * @param {String} [option] The option name
  677. * @return {String|Object}
  678. */
  679. getOptions: function(field, validator, option) {
  680. if (!field) {
  681. return this.options;
  682. }
  683. if ('object' === typeof field) {
  684. field = field.attr('data-bv-field');
  685. }
  686. if (!this.options.fields[field]) {
  687. return null;
  688. }
  689. var options = this.options.fields[field];
  690. if (!validator) {
  691. return option ? options[option] : options;
  692. }
  693. if (!options.validators || !options.validators[validator]) {
  694. return null;
  695. }
  696. return option ? options.validators[validator][option] : options.validators[validator];
  697. },
  698. /**
  699. * Disable/enable submit buttons
  700. *
  701. * @param {Boolean} disabled Can be true or false
  702. * @returns {BootstrapValidator}
  703. */
  704. disableSubmitButtons: function(disabled) {
  705. if (!disabled) {
  706. this.$form.find(this.options.submitButtons).removeAttr('disabled');
  707. } else if (this.options.live !== 'disabled') {
  708. // Don't disable if the live validating mode is disabled
  709. this.$form.find(this.options.submitButtons).attr('disabled', 'disabled');
  710. }
  711. return this;
  712. },
  713. /**
  714. * Validate the form
  715. *
  716. * @returns {BootstrapValidator}
  717. */
  718. validate: function() {
  719. if (!this.options.fields) {
  720. return this;
  721. }
  722. this.disableSubmitButtons(true);
  723. for (var field in this.options.fields) {
  724. this.validateField(field);
  725. }
  726. this._submit();
  727. return this;
  728. },
  729. /**
  730. * Validate given field
  731. *
  732. * @param {String|jQuery} field The field name or field element
  733. * @returns {BootstrapValidator}
  734. */
  735. validateField: function(field) {
  736. var fields = $([]);
  737. switch (typeof field) {
  738. case 'object':
  739. fields = field;
  740. field = field.attr('data-bv-field');
  741. break;
  742. case 'string':
  743. fields = this.getFieldElements(field);
  744. break;
  745. default:
  746. break;
  747. }
  748. if (fields.length === 0 || (this.options.fields[field] && this.options.fields[field].enabled === false)) {
  749. return this;
  750. }
  751. var that = this,
  752. type = fields.attr('type'),
  753. total = ('radio' === type || 'checkbox' === type) ? 1 : fields.length,
  754. updateAll = ('radio' === type || 'checkbox' === type),
  755. validators = this.options.fields[field].validators,
  756. verbose = this.options.fields[field].verbose === 'true' || this.options.fields[field].verbose === true || this.options.verbose === 'true' || this.options.verbose === true,
  757. validatorName,
  758. validateResult;
  759. for (var i = 0; i < total; i++) {
  760. var $field = fields.eq(i);
  761. if (this._isExcluded($field)) {
  762. continue;
  763. }
  764. var stop = false;
  765. for (validatorName in validators) {
  766. if ($field.data('bv.dfs.' + validatorName)) {
  767. $field.data('bv.dfs.' + validatorName).reject();
  768. }
  769. if (stop) {
  770. break;
  771. }
  772. // Don't validate field if it is already done
  773. var result = $field.data('bv.result.' + validatorName);
  774. if (result === this.STATUS_VALID || result === this.STATUS_INVALID) {
  775. this._onFieldValidated($field, validatorName);
  776. continue;
  777. } else if (validators[validatorName].enabled === false) {
  778. this.updateStatus(updateAll ? field : $field, this.STATUS_VALID, validatorName);
  779. continue;
  780. }
  781. $field.data('bv.result.' + validatorName, this.STATUS_VALIDATING);
  782. validateResult = $.fn.bootstrapValidator.validators[validatorName].validate(this, $field, validators[validatorName]);
  783. // validateResult can be a $.Deferred object ...
  784. if ('object' === typeof validateResult && validateResult.resolve) {
  785. this.updateStatus(updateAll ? field : $field, this.STATUS_VALIDATING, validatorName);
  786. $field.data('bv.dfs.' + validatorName, validateResult);
  787. validateResult.done(function($f, v, response) {
  788. // v is validator name
  789. $f.removeData('bv.dfs.' + v).data('bv.response.' + v, response);
  790. if (response.message) {
  791. that.updateMessage($f, v, response.message);
  792. }
  793. that.updateStatus(updateAll ? $f.attr('data-bv-field') : $f, response.valid ? that.STATUS_VALID : that.STATUS_INVALID, v);
  794. if (response.valid && that._submitIfValid === true) {
  795. // If a remote validator returns true and the form is ready to submit, then do it
  796. that._submit();
  797. } else if (!response.valid && !verbose) {
  798. stop = true;
  799. }
  800. });
  801. }
  802. // ... or object { valid: true/false, message: 'dynamic message' }
  803. else if ('object' === typeof validateResult && validateResult.valid !== undefined && validateResult.message !== undefined) {
  804. $field.data('bv.response.' + validatorName, validateResult);
  805. this.updateMessage(updateAll ? field : $field, validatorName, validateResult.message);
  806. this.updateStatus(updateAll ? field : $field, validateResult.valid ? this.STATUS_VALID : this.STATUS_INVALID, validatorName);
  807. if (!validateResult.valid && !verbose) {
  808. break;
  809. }
  810. }
  811. // ... or a boolean value
  812. else if ('boolean' === typeof validateResult) {
  813. $field.data('bv.response.' + validatorName, validateResult);
  814. this.updateStatus(updateAll ? field : $field, validateResult ? this.STATUS_VALID : this.STATUS_INVALID, validatorName);
  815. if (!validateResult && !verbose) {
  816. break;
  817. }
  818. }
  819. }
  820. }
  821. return this;
  822. },
  823. /**
  824. * Update the error message
  825. *
  826. * @param {String|jQuery} field The field name or field element
  827. * @param {String} validator The validator name
  828. * @param {String} message The message
  829. * @returns {BootstrapValidator}
  830. */
  831. updateMessage: function(field, validator, message) {
  832. var $fields = $([]);
  833. switch (typeof field) {
  834. case 'object':
  835. $fields = field;
  836. field = field.attr('data-bv-field');
  837. break;
  838. case 'string':
  839. $fields = this.getFieldElements(field);
  840. break;
  841. default:
  842. break;
  843. }
  844. $fields.each(function() {
  845. $(this).data('bv.messages').find('.help-block[data-bv-validator="' + validator + '"][data-bv-for="' + field + '"]').html(message);
  846. });
  847. },
  848. /**
  849. * Update all validating results of field
  850. *
  851. * @param {String|jQuery} field The field name or field element
  852. * @param {String} status The status. Can be 'NOT_VALIDATED', 'VALIDATING', 'INVALID' or 'VALID'
  853. * @param {String} [validatorName] The validator name. If null, the method updates validity result for all validators
  854. * @returns {BootstrapValidator}
  855. */
  856. updateStatus: function(field, status, validatorName) {
  857. var fields = $([]);
  858. switch (typeof field) {
  859. case 'object':
  860. fields = field;
  861. field = field.attr('data-bv-field');
  862. break;
  863. case 'string':
  864. fields = this.getFieldElements(field);
  865. break;
  866. default:
  867. break;
  868. }
  869. if (status === this.STATUS_NOT_VALIDATED) {
  870. // Reset the flag
  871. this._submitIfValid = false;
  872. }
  873. var that = this,
  874. type = fields.attr('type'),
  875. group = this.options.fields[field].group || this.options.group,
  876. total = ('radio' === type || 'checkbox' === type) ? 1 : fields.length;
  877. for (var i = 0; i < total; i++) {
  878. var $field = fields.eq(i);
  879. if (this._isExcluded($field)) {
  880. continue;
  881. }
  882. var $parent = $field.parents(group),
  883. $message = $field.data('bv.messages'),
  884. $allErrors = $message.find('.help-block[data-bv-validator][data-bv-for="' + field + '"]'),
  885. $errors = validatorName ? $allErrors.filter('[data-bv-validator="' + validatorName + '"]') : $allErrors,
  886. $icon = $parent.find('.form-control-feedback[data-bv-icon-for="' + field + '"]'),
  887. container = ('function' === typeof (this.options.fields[field].container || this.options.container)) ? (this.options.fields[field].container || this.options.container).call(this, $field, this) : (this.options.fields[field].container || this.options.container),
  888. isValidField = null;
  889. // Update status
  890. if (validatorName) {
  891. $field.data('bv.result.' + validatorName, status);
  892. } else {
  893. for (var v in this.options.fields[field].validators) {
  894. $field.data('bv.result.' + v, status);
  895. }
  896. }
  897. // Show/hide error elements and feedback icons
  898. $errors.attr('data-bv-result', status);
  899. // Determine the tab containing the element
  900. var $tabPane = $field.parents('.tab-pane'),
  901. tabId, $tab;
  902. if ($tabPane && (tabId = $tabPane.attr('id'))) {
  903. $tab = $('a[href="#' + tabId + '"][data-toggle="tab"]').parent();
  904. }
  905. switch (status) {
  906. case this.STATUS_VALIDATING:
  907. isValidField = null;
  908. this.disableSubmitButtons(true);
  909. $parent.removeClass('has-success').removeClass('has-error');
  910. if ($icon) {
  911. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).addClass(this.options.feedbackIcons.validating).show();
  912. }
  913. if ($tab) {
  914. $tab.removeClass('bv-tab-success').removeClass('bv-tab-error');
  915. }
  916. break;
  917. case this.STATUS_INVALID:
  918. isValidField = false;
  919. this.disableSubmitButtons(true);
  920. $parent.removeClass('has-success').addClass('has-error');
  921. if ($icon) {
  922. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.validating).addClass(this.options.feedbackIcons.invalid).show();
  923. }
  924. if ($tab) {
  925. $tab.removeClass('bv-tab-success').addClass('bv-tab-error');
  926. }
  927. break;
  928. case this.STATUS_VALID:
  929. // If the field is valid (passes all validators)
  930. isValidField = ($allErrors.filter('[data-bv-result="' + this.STATUS_NOT_VALIDATED +'"]').length === 0)
  931. ? ($allErrors.filter('[data-bv-result="' + this.STATUS_VALID +'"]').length === $allErrors.length) // All validators are completed
  932. : null; // There are some validators that have not done
  933. if (isValidField !== null) {
  934. this.disableSubmitButtons(this.$submitButton ? !this.isValid() : !isValidField);
  935. if ($icon) {
  936. $icon
  937. .removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).removeClass(this.options.feedbackIcons.valid)
  938. .addClass(isValidField ? this.options.feedbackIcons.valid : this.options.feedbackIcons.invalid)
  939. .show();
  940. }
  941. }
  942. $parent.removeClass('has-error has-success').addClass(this.isValidContainer($parent) ? 'has-success' : 'has-error');
  943. if ($tab) {
  944. $tab.removeClass('bv-tab-success').removeClass('bv-tab-error').addClass(this.isValidContainer($tabPane) ? 'bv-tab-success' : 'bv-tab-error');
  945. }
  946. break;
  947. case this.STATUS_NOT_VALIDATED:
  948. /* falls through */
  949. default:
  950. isValidField = null;
  951. this.disableSubmitButtons(false);
  952. $parent.removeClass('has-success').removeClass('has-error');
  953. if ($icon) {
  954. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).hide();
  955. }
  956. if ($tab) {
  957. $tab.removeClass('bv-tab-success').removeClass('bv-tab-error');
  958. }
  959. break;
  960. }
  961. switch (true) {
  962. // Only show the first error message if it is placed inside a tooltip ...
  963. case ($icon && 'tooltip' === container):
  964. (isValidField === false)
  965. ? $icon.css('cursor', 'pointer').tooltip('destroy').tooltip({
  966. container: 'body',
  967. html: true,
  968. placement: 'top',
  969. title: $allErrors.filter('[data-bv-result="' + that.STATUS_INVALID + '"]').eq(0).html()
  970. })
  971. : $icon.tooltip('hide');
  972. break;
  973. // ... or popover
  974. case ($icon && 'popover' === container):
  975. (isValidField === false)
  976. ? $icon.css('cursor', 'pointer').popover('destroy').popover({
  977. container: 'body',
  978. content: $allErrors.filter('[data-bv-result="' + that.STATUS_INVALID + '"]').eq(0).html(),
  979. html: true,
  980. placement: 'top',
  981. trigger: 'hover click'
  982. })
  983. : $icon.popover('hide');
  984. break;
  985. default:
  986. (status === this.STATUS_INVALID) ? $errors.show() : $errors.hide();
  987. break;
  988. }
  989. // Trigger an event
  990. $field.trigger($.Event(this.options.events.fieldStatus), {
  991. bv: this,
  992. field: field,
  993. element: $field,
  994. status: status
  995. });
  996. this._onFieldValidated($field, validatorName);
  997. }
  998. return this;
  999. },
  1000. /**
  1001. * Check the form validity
  1002. *
  1003. * @returns {Boolean}
  1004. */
  1005. isValid: function() {
  1006. for (var field in this.options.fields) {
  1007. if (!this.isValidField(field)) {
  1008. return false;
  1009. }
  1010. }
  1011. return true;
  1012. },
  1013. /**
  1014. * Check if the field is valid or not
  1015. *
  1016. * @param {String|jQuery} field The field name or field element
  1017. * @returns {Boolean}
  1018. */
  1019. isValidField: function(field) {
  1020. var fields = $([]);
  1021. switch (typeof field) {
  1022. case 'object':
  1023. fields = field;
  1024. field = field.attr('data-bv-field');
  1025. break;
  1026. case 'string':
  1027. fields = this.getFieldElements(field);
  1028. break;
  1029. default:
  1030. break;
  1031. }
  1032. if (fields.length === 0 || this.options.fields[field] === null || this.options.fields[field].enabled === false) {
  1033. return true;
  1034. }
  1035. var type = fields.attr('type'),
  1036. total = ('radio' === type || 'checkbox' === type) ? 1 : fields.length,
  1037. $field, validatorName, status;
  1038. for (var i = 0; i < total; i++) {
  1039. $field = fields.eq(i);
  1040. if (this._isExcluded($field)) {
  1041. continue;
  1042. }
  1043. for (validatorName in this.options.fields[field].validators) {
  1044. if (this.options.fields[field].validators[validatorName].enabled === false) {
  1045. continue;
  1046. }
  1047. status = $field.data('bv.result.' + validatorName);
  1048. if (status !== this.STATUS_VALID) {
  1049. return false;
  1050. }
  1051. }
  1052. }
  1053. return true;
  1054. },
  1055. /**
  1056. * Check if all fields inside a given container are valid.
  1057. * It's useful when working with a wizard-like such as tab, collapse
  1058. *
  1059. * @param {String|jQuery} container The container selector or element
  1060. * @returns {Boolean}
  1061. */
  1062. isValidContainer: function(container) {
  1063. var that = this,
  1064. map = {},
  1065. $container = ('string' === typeof container) ? $(container) : container;
  1066. if ($container.length === 0) {
  1067. return true;
  1068. }
  1069. $container.find('[data-bv-field]').each(function() {
  1070. var $field = $(this),
  1071. field = $field.attr('data-bv-field');
  1072. if (!that._isExcluded($field) && !map[field]) {
  1073. map[field] = $field;
  1074. }
  1075. });
  1076. for (var field in map) {
  1077. var $f = map[field];
  1078. if ($f.data('bv.messages')
  1079. .find('.help-block[data-bv-validator][data-bv-for="' + field + '"]')
  1080. .filter('[data-bv-result="' + this.STATUS_INVALID +'"]')
  1081. .length > 0)
  1082. {
  1083. return false;
  1084. }
  1085. }
  1086. return true;
  1087. },
  1088. /**
  1089. * Submit the form using default submission.
  1090. * It also does not perform any validations when submitting the form
  1091. */
  1092. defaultSubmit: function() {
  1093. if (this.$submitButton) {
  1094. // Create hidden input to send the submit buttons
  1095. $('<input/>')
  1096. .attr('type', 'hidden')
  1097. .attr('data-bv-submit-hidden', '')
  1098. .attr('name', this.$submitButton.attr('name'))
  1099. .val(this.$submitButton.val())
  1100. .appendTo(this.$form);
  1101. }
  1102. // Submit form
  1103. this.$form.off('submit.bv').submit();
  1104. },
  1105. // ---
  1106. // Useful APIs which aren't used internally
  1107. // ---
  1108. /**
  1109. * Get the list of invalid fields
  1110. *
  1111. * @returns {jQuery[]}
  1112. */
  1113. getInvalidFields: function() {
  1114. return this.$invalidFields;
  1115. },
  1116. /**
  1117. * Returns the clicked submit button
  1118. *
  1119. * @returns {jQuery}
  1120. */
  1121. getSubmitButton: function() {
  1122. return this.$submitButton;
  1123. },
  1124. /**
  1125. * Get the error messages
  1126. *
  1127. * @param {String|jQuery} [field] The field name or field element
  1128. * If the field is not defined, the method returns all error messages of all fields
  1129. * @param {String} [validator] The name of validator
  1130. * If the validator is not defined, the method returns error messages of all validators
  1131. * @returns {String[]}
  1132. */
  1133. getMessages: function(field, validator) {
  1134. var that = this,
  1135. messages = [],
  1136. $fields = $([]);
  1137. switch (true) {
  1138. case (field && 'object' === typeof field):
  1139. $fields = field;
  1140. break;
  1141. case (field && 'string' === typeof field):
  1142. var f = this.getFieldElements(field);
  1143. if (f.length > 0) {
  1144. var type = f.attr('type');
  1145. $fields = ('radio' === type || 'checkbox' === type) ? f.eq(0) : f;
  1146. }
  1147. break;
  1148. default:
  1149. $fields = this.$invalidFields;
  1150. break;
  1151. }
  1152. var filter = validator ? '[data-bv-validator="' + validator + '"]' : '';
  1153. $fields.each(function() {
  1154. messages = messages.concat(
  1155. $(this)
  1156. .data('bv.messages')
  1157. .find('.help-block[data-bv-for="' + $(this).attr('data-bv-field') + '"][data-bv-result="' + that.STATUS_INVALID + '"]' + filter)
  1158. .map(function() {
  1159. var v = $(this).attr('data-bv-validator'),
  1160. f = $(this).attr('data-bv-for');
  1161. return (that.options.fields[f].validators[v].enabled === false) ? '' : $(this).html();
  1162. })
  1163. .get()
  1164. );
  1165. });
  1166. return messages;
  1167. },
  1168. /**
  1169. * Update the option of a specific validator
  1170. *
  1171. * @param {String|jQuery} field The field name or field element
  1172. * @param {String} validator The validator name
  1173. * @param {String} option The option name
  1174. * @param {String} value The value to set
  1175. * @returns {BootstrapValidator}
  1176. */
  1177. updateOption: function(field, validator, option, value) {
  1178. if ('object' === typeof field) {
  1179. field = field.attr('data-bv-field');
  1180. }
  1181. if (this.options.fields[field] && this.options.fields[field].validators[validator]) {
  1182. this.options.fields[field].validators[validator][option] = value;
  1183. this.updateStatus(field, this.STATUS_NOT_VALIDATED, validator);
  1184. }
  1185. return this;
  1186. },
  1187. /**
  1188. * Add a new field
  1189. *
  1190. * @param {String|jQuery} field The field name or field element
  1191. * @param {Object} [options] The validator rules
  1192. * @returns {BootstrapValidator}
  1193. */
  1194. addField: function(field, options) {
  1195. var fields = $([]);
  1196. switch (typeof field) {
  1197. case 'object':
  1198. fields = field;
  1199. field = field.attr('data-bv-field') || field.attr('name');
  1200. break;
  1201. case 'string':
  1202. delete this._cacheFields[field];
  1203. fields = this.getFieldElements(field);
  1204. break;
  1205. default:
  1206. break;
  1207. }
  1208. fields.attr('data-bv-field', field);
  1209. var type = fields.attr('type'),
  1210. total = ('radio' === type || 'checkbox' === type) ? 1 : fields.length;
  1211. for (var i = 0; i < total; i++) {
  1212. var $field = fields.eq(i);
  1213. // Try to parse the options from HTML attributes
  1214. var opts = this._parseOptions($field);
  1215. opts = (opts === null) ? options : $.extend(true, options, opts);
  1216. this.options.fields[field] = $.extend(true, this.options.fields[field], opts);
  1217. // Update the cache
  1218. this._cacheFields[field] = this._cacheFields[field] ? this._cacheFields[field].add($field) : $field;
  1219. // Init the element
  1220. this._initField(('checkbox' === type || 'radio' === type) ? field : $field);
  1221. }
  1222. this.disableSubmitButtons(false);
  1223. // Trigger an event
  1224. this.$form.trigger($.Event(this.options.events.fieldAdded), {
  1225. field: field,
  1226. element: fields,
  1227. options: this.options.fields[field]
  1228. });
  1229. return this;
  1230. },
  1231. /**
  1232. * Remove a given field
  1233. *
  1234. * @param {String|jQuery} field The field name or field element
  1235. * @returns {BootstrapValidator}
  1236. */
  1237. removeField: function(field) {
  1238. var fields = $([]);
  1239. switch (typeof field) {
  1240. case 'object':
  1241. fields = field;
  1242. field = field.attr('data-bv-field') || field.attr('name');
  1243. fields.attr('data-bv-field', field);
  1244. break;
  1245. case 'string':
  1246. fields = this.getFieldElements(field);
  1247. break;
  1248. default:
  1249. break;
  1250. }
  1251. if (fields.length === 0) {
  1252. return this;
  1253. }
  1254. var type = fields.attr('type'),
  1255. total = ('radio' === type || 'checkbox' === type) ? 1 : fields.length;
  1256. for (var i = 0; i < total; i++) {
  1257. var $field = fields.eq(i);
  1258. // Remove from the list of invalid fields
  1259. this.$invalidFields = this.$invalidFields.not($field);
  1260. // Update the cache
  1261. this._cacheFields[field] = this._cacheFields[field].not($field);
  1262. }
  1263. if (!this._cacheFields[field] || this._cacheFields[field].length === 0) {
  1264. delete this.options.fields[field];
  1265. }
  1266. if ('checkbox' === type || 'radio' === type) {
  1267. this._initField(field);
  1268. }
  1269. this.disableSubmitButtons(false);
  1270. // Trigger an event
  1271. this.$form.trigger($.Event(this.options.events.fieldRemoved), {
  1272. field: field,
  1273. element: fields
  1274. });
  1275. return this;
  1276. },
  1277. /**
  1278. * Reset given field
  1279. *
  1280. * @param {String|jQuery} field The field name or field element
  1281. * @param {Boolean} [resetValue] If true, the method resets field value to empty or remove checked/selected attribute (for radio/checkbox)
  1282. * @returns {BootstrapValidator}
  1283. */
  1284. resetField: function(field, resetValue) {
  1285. var $fields = $([]);
  1286. switch (typeof field) {
  1287. case 'object':
  1288. $fields = field;
  1289. field = field.attr('data-bv-field');
  1290. break;
  1291. case 'string':
  1292. $fields = this.getFieldElements(field);
  1293. break;
  1294. default:
  1295. break;
  1296. }
  1297. var total = $fields.length;
  1298. if (this.options.fields[field]) {
  1299. for (var i = 0; i < total; i++) {
  1300. for (var validator in this.options.fields[field].validators) {
  1301. $fields.eq(i).removeData('bv.dfs.' + validator);
  1302. }
  1303. }
  1304. }
  1305. // Mark field as not validated yet
  1306. this.updateStatus(field, this.STATUS_NOT_VALIDATED);
  1307. if (resetValue) {
  1308. var type = $fields.attr('type');
  1309. ('radio' === type || 'checkbox' === type) ? $fields.removeAttr('checked').removeAttr('selected') : $fields.val('');
  1310. }
  1311. return this;
  1312. },
  1313. /**
  1314. * Reset the form
  1315. *
  1316. * @param {Boolean} [resetValue] If true, the method resets field value to empty or remove checked/selected attribute (for radio/checkbox)
  1317. * @returns {BootstrapValidator}
  1318. */
  1319. resetForm: function(resetValue) {
  1320. for (var field in this.options.fields) {
  1321. this.resetField(field, resetValue);
  1322. }
  1323. this.$invalidFields = $([]);
  1324. this.$submitButton = null;
  1325. // Enable submit buttons
  1326. this.disableSubmitButtons(false);
  1327. return this;
  1328. },
  1329. /**
  1330. * Revalidate given field
  1331. * It's used when you need to revalidate the field which its value is updated by other plugin
  1332. *
  1333. * @param {String|jQuery} field The field name of field element
  1334. * @returns {BootstrapValidator}
  1335. */
  1336. revalidateField: function(field) {
  1337. this.updateStatus(field, this.STATUS_NOT_VALIDATED)
  1338. .validateField(field);
  1339. return this;
  1340. },
  1341. /**
  1342. * Enable/Disable all validators to given field
  1343. *
  1344. * @param {String} field The field name
  1345. * @param {Boolean} enabled Enable/Disable field validators
  1346. * @param {String} [validatorName] The validator name. If null, all validators will be enabled/disabled
  1347. * @returns {BootstrapValidator}
  1348. */
  1349. enableFieldValidators: function(field, enabled, validatorName) {
  1350. var validators = this.options.fields[field].validators;
  1351. // Enable/disable particular validator
  1352. if (validatorName
  1353. && validators
  1354. && validators[validatorName] && validators[validatorName].enabled !== enabled)
  1355. {
  1356. this.options.fields[field].validators[validatorName].enabled = enabled;
  1357. this.updateStatus(field, this.STATUS_NOT_VALIDATED, validatorName);
  1358. }
  1359. // Enable/disable all validators
  1360. else if (!validatorName && this.options.fields[field].enabled !== enabled) {
  1361. this.options.fields[field].enabled = enabled;
  1362. for (var v in validators) {
  1363. this.enableFieldValidators(field, enabled, v);
  1364. }
  1365. }
  1366. return this;
  1367. },
  1368. /**
  1369. * Some validators have option which its value is dynamic.
  1370. * For example, the zipCode validator has the country option which might be changed dynamically by a select element.
  1371. *
  1372. * @param {jQuery|String} field The field name or element
  1373. * @param {String|Function} option The option which can be determined by:
  1374. * - a string
  1375. * - name of field which defines the value
  1376. * - name of function which returns the value
  1377. * - a function returns the value
  1378. *
  1379. * The callback function has the format of
  1380. * callback: function(value, validator, $field) {
  1381. * // value is the value of field
  1382. * // validator is the BootstrapValidator instance
  1383. * // $field is the field element
  1384. * }
  1385. *
  1386. * @returns {String}
  1387. */
  1388. getDynamicOption: function(field, option) {
  1389. var $field = ('string' === typeof field) ? this.getFieldElements(field) : field,
  1390. value = $field.val();
  1391. // Option can be determined by
  1392. // ... a function
  1393. if ('function' === typeof option) {
  1394. return $.fn.bootstrapValidator.helpers.call(option, [value, this, $field]);
  1395. }
  1396. // ... value of other field
  1397. else if ('string' === typeof option) {
  1398. var $f = this.getFieldElements(option);
  1399. if ($f.length) {
  1400. return $f.val();
  1401. }
  1402. // ... return value of callback
  1403. else {
  1404. return $.fn.bootstrapValidator.helpers.call(option, [value, this, $field]) || option;
  1405. }
  1406. }
  1407. return null;
  1408. },
  1409. /**
  1410. * Destroy the plugin
  1411. * It will remove all error messages, feedback icons and turn off the events
  1412. */
  1413. destroy: function() {
  1414. var field, fields, $field, validator, $icon, group;
  1415. for (field in this.options.fields) {
  1416. fields = this.getFieldElements(field);
  1417. group = this.options.fields[field].group || this.options.group;
  1418. for (var i = 0; i < fields.length; i++) {
  1419. $field = fields.eq(i);
  1420. $field
  1421. // Remove all error messages
  1422. .data('bv.messages')
  1423. .find('.help-block[data-bv-validator][data-bv-for="' + field + '"]').remove().end()
  1424. .end()
  1425. .removeData('bv.messages')
  1426. // Remove feedback classes
  1427. .parents(group)
  1428. .removeClass('has-feedback has-error has-success')
  1429. .end()
  1430. // Turn off events
  1431. .off('.bv')
  1432. .removeAttr('data-bv-field');
  1433. // Remove feedback icons, tooltip/popover container
  1434. $icon = $field.parents(group).find('i[data-bv-icon-for="' + field + '"]');
  1435. if ($icon) {
  1436. var container = ('function' === typeof (this.options.fields[field].container || this.options.container)) ? (this.options.fields[field].container || this.options.container).call(this, $field, this) : (this.options.fields[field].container || this.options.container);
  1437. switch (container) {
  1438. case 'tooltip':
  1439. $icon.tooltip('destroy').remove();
  1440. break;
  1441. case 'popover':
  1442. $icon.popover('destroy').remove();
  1443. break;
  1444. default:
  1445. $icon.remove();
  1446. break;
  1447. }
  1448. }
  1449. for (validator in this.options.fields[field].validators) {
  1450. if ($field.data('bv.dfs.' + validator)) {
  1451. $field.data('bv.dfs.' + validator).reject();
  1452. }
  1453. $field.removeData('bv.result.' + validator)
  1454. .removeData('bv.response.' + validator)
  1455. .removeData('bv.dfs.' + validator);
  1456. // Destroy the validator
  1457. if ('function' === typeof $.fn.bootstrapValidator.validators[validator].destroy) {
  1458. $.fn.bootstrapValidator.validators[validator].destroy(this, $field, this.options.fields[field].validators[validator]);
  1459. }
  1460. }
  1461. }
  1462. }
  1463. this.disableSubmitButtons(false); // Enable submit buttons
  1464. this.$hiddenButton.remove(); // Remove the hidden button
  1465. this.$form
  1466. .removeClass(this.options.elementClass)
  1467. .off('.bv')
  1468. .removeData('bootstrapValidator')
  1469. // Remove generated hidden elements
  1470. .find('[data-bv-submit-hidden]').remove().end()
  1471. .find('[type="submit"]').off('click.bv');
  1472. }
  1473. };
  1474. // Plugin definition
  1475. $.fn.bootstrapValidator = function(option) {
  1476. var params = arguments;
  1477. return this.each(function() {
  1478. var $this = $(this),
  1479. data = $this.data('bootstrapValidator'),
  1480. options = 'object' === typeof option && option;
  1481. if (!data) {
  1482. data = new BootstrapValidator(this, options);
  1483. $this.data('bootstrapValidator', data);
  1484. }
  1485. // Allow to call plugin method
  1486. if ('string' === typeof option) {
  1487. data[option].apply(data, Array.prototype.slice.call(params, 1));
  1488. }
  1489. });
  1490. };
  1491. // The default options
  1492. $.fn.bootstrapValidator.DEFAULT_OPTIONS = {
  1493. // The form CSS class
  1494. elementClass: 'bv-form',
  1495. // Default invalid message
  1496. message: 'This value is not valid',
  1497. // The CSS selector for indicating the element consists the field
  1498. // By default, each field is placed inside the <div class="form-group"></div>
  1499. // You should adjust this option if your form group consists of many fields which not all of them need to be validated
  1500. group: '.form-group',
  1501. //The error messages container. It can be:
  1502. // - 'tooltip' if you want to use Bootstrap tooltip to show error messages
  1503. // - 'popover' if you want to use Bootstrap popover to show error messages
  1504. // - a CSS selector indicating the container
  1505. // In the first two cases, since the tooltip/popover should be small enough, the plugin only shows only one error message
  1506. // You also can define the message container for particular field
  1507. container: null,
  1508. // The field will not be live validated if its length is less than this number of characters
  1509. threshold: null,
  1510. // Indicate fields which won't be validated
  1511. // By default, the plugin will not validate the following kind of fields:
  1512. // - disabled
  1513. // - hidden
  1514. // - invisible
  1515. //
  1516. // The setting consists of jQuery filters. Accept 3 formats:
  1517. // - A string. Use a comma to separate filter
  1518. // - An array. Each element is a filter
  1519. // - An array. Each element can be a callback function
  1520. // function($field, validator) {
  1521. // $field is jQuery object representing the field element
  1522. // validator is the BootstrapValidator instance
  1523. // return true or false;
  1524. // }
  1525. //
  1526. // The 3 following settings are equivalent:
  1527. //
  1528. // 1) ':disabled, :hidden, :not(:visible)'
  1529. // 2) [':disabled', ':hidden', ':not(:visible)']
  1530. // 3) [':disabled', ':hidden', function($field) {
  1531. // return !$field.is(':visible');
  1532. // }]
  1533. excluded: [':disabled', ':hidden', ':not(:visible)'],
  1534. // Shows ok/error/loading icons based on the field validity.
  1535. // This feature requires Bootstrap v3.1.0 or later (http://getbootstrap.com/css/#forms-control-validation).
  1536. // Since Bootstrap doesn't provide any methods to know its version, this option cannot be on/off automatically.
  1537. // In other word, to use this feature you have to upgrade your Bootstrap to v3.1.0 or later.
  1538. //
  1539. // Examples:
  1540. // - Use Glyphicons icons:
  1541. // feedbackIcons: {
  1542. // valid: 'glyphicon glyphicon-ok',
  1543. // invalid: 'glyphicon glyphicon-remove',
  1544. // validating: 'glyphicon glyphicon-refresh'
  1545. // }
  1546. // - Use FontAwesome icons:
  1547. // feedbackIcons: {
  1548. // valid: 'fa fa-check',
  1549. // invalid: 'fa fa-times',
  1550. // validating: 'fa fa-refresh'
  1551. // }
  1552. feedbackIcons: {
  1553. valid: null,
  1554. invalid: null,
  1555. validating: null
  1556. },
  1557. // The submit buttons selector
  1558. // These buttons will be disabled to prevent the valid form from multiple submissions
  1559. submitButtons: '[type="submit"]',
  1560. // Live validating option
  1561. // Can be one of 3 values:
  1562. // - enabled: The plugin validates fields as soon as they are changed
  1563. // - disabled: Disable the live validating. The error messages are only shown after the form is submitted
  1564. // - submitted: The live validating is enabled after the form is submitted
  1565. live: 'enabled',
  1566. // Map the field name with validator rules
  1567. fields: null,
  1568. // Use custom event name to avoid window.onerror being invoked by jQuery
  1569. // See https://github.com/nghuuphuoc/bootstrapvalidator/issues/630
  1570. events: {
  1571. formInit: 'init.form.bv',
  1572. formError: 'error.form.bv',
  1573. formSuccess: 'success.form.bv',
  1574. fieldAdded: 'added.field.bv',
  1575. fieldRemoved: 'removed.field.bv',
  1576. fieldInit: 'init.field.bv',
  1577. fieldError: 'error.field.bv',
  1578. fieldSuccess: 'success.field.bv',
  1579. fieldStatus: 'status.field.bv',
  1580. validatorError: 'error.validator.bv',
  1581. validatorSuccess: 'success.validator.bv'
  1582. },
  1583. // Whether to be verbose when validating a field or not.
  1584. // Possible values:
  1585. // - true: when a field has multiple validators, all of them will be checked, and respectively - if errors occur in
  1586. // multiple validators, all of them will be displayed to the user
  1587. // - false: when a field has multiple validators, validation for this field will be terminated upon the first encountered error.
  1588. // Thus, only the very first error message related to this field will be displayed to the user
  1589. verbose: true
  1590. };
  1591. // Available validators
  1592. $.fn.bootstrapValidator.validators = {};
  1593. // i18n
  1594. $.fn.bootstrapValidator.i18n = {};
  1595. $.fn.bootstrapValidator.Constructor = BootstrapValidator;
  1596. // Helper methods, which can be used in validator class
  1597. $.fn.bootstrapValidator.helpers = {
  1598. /**
  1599. * Execute a callback function
  1600. *
  1601. * @param {String|Function} functionName Can be
  1602. * - name of global function
  1603. * - name of namespace function (such as A.B.C)
  1604. * - a function
  1605. * @param {Array} args The callback arguments
  1606. */
  1607. call: function(functionName, args) {
  1608. if ('function' === typeof functionName) {
  1609. return functionName.apply(this, args);
  1610. } else if ('string' === typeof functionName) {
  1611. if ('()' === functionName.substring(functionName.length - 2)) {
  1612. functionName = functionName.substring(0, functionName.length - 2);
  1613. }
  1614. var ns = functionName.split('.'),
  1615. func = ns.pop(),
  1616. context = window;
  1617. for (var i = 0; i < ns.length; i++) {
  1618. context = context[ns[i]];
  1619. }
  1620. return (typeof context[func] === 'undefined') ? null : context[func].apply(this, args);
  1621. }
  1622. },
  1623. /**
  1624. * Format a string
  1625. * It's used to format the error message
  1626. * format('The field must between %s and %s', [10, 20]) = 'The field must between 10 and 20'
  1627. *
  1628. * @param {String} message
  1629. * @param {Array} parameters
  1630. * @returns {String}
  1631. */
  1632. format: function(message, parameters) {
  1633. if (!$.isArray(parameters)) {
  1634. parameters = [parameters];
  1635. }
  1636. for (var i in parameters) {
  1637. message = message.replace('%s', parameters[i]);
  1638. }
  1639. return message;
  1640. },
  1641. /**
  1642. * Validate a date
  1643. *
  1644. * @param {Number} year The full year in 4 digits
  1645. * @param {Number} month The month number
  1646. * @param {Number} day The day number
  1647. * @param {Boolean} [notInFuture] If true, the date must not be in the future
  1648. * @returns {Boolean}
  1649. */
  1650. date: function(year, month, day, notInFuture) {
  1651. if (isNaN(year) || isNaN(month) || isNaN(day)) {
  1652. return false;
  1653. }
  1654. if (day.length > 2 || month.length > 2 || year.length > 4) {
  1655. return false;
  1656. }
  1657. day = parseInt(day, 10);
  1658. month = parseInt(month, 10);
  1659. year = parseInt(year, 10);
  1660. if (year < 1000 || year > 9999 || month <= 0 || month > 12) {
  1661. return false;
  1662. }
  1663. var numDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  1664. // Update the number of days in Feb of leap year
  1665. if (year % 400 === 0 || (year % 100 !== 0 && year % 4 === 0)) {
  1666. numDays[1] = 29;
  1667. }
  1668. // Check the day
  1669. if (day <= 0 || day > numDays[month - 1]) {
  1670. return false;
  1671. }
  1672. if (notInFuture === true) {
  1673. var currentDate = new Date(),
  1674. currentYear = currentDate.getFullYear(),
  1675. currentMonth = currentDate.getMonth(),
  1676. currentDay = currentDate.getDate();
  1677. return (year < currentYear
  1678. || (year === currentYear && month - 1 < currentMonth)
  1679. || (year === currentYear && month - 1 === currentMonth && day < currentDay));
  1680. }
  1681. return true;
  1682. },
  1683. /**
  1684. * Implement Luhn validation algorithm
  1685. * Credit to https://gist.github.com/ShirtlessKirk/2134376
  1686. *
  1687. * @see http://en.wikipedia.org/wiki/Luhn
  1688. * @param {String} value
  1689. * @returns {Boolean}
  1690. */
  1691. luhn: function(value) {
  1692. var length = value.length,
  1693. mul = 0,
  1694. prodArr = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]],
  1695. sum = 0;
  1696. while (length--) {
  1697. sum += prodArr[mul][parseInt(value.charAt(length), 10)];
  1698. mul ^= 1;
  1699. }
  1700. return (sum % 10 === 0 && sum > 0);
  1701. },
  1702. /**
  1703. * Implement modulus 11, 10 (ISO 7064) algorithm
  1704. *
  1705. * @param {String} value
  1706. * @returns {Boolean}
  1707. */
  1708. mod11And10: function(value) {
  1709. var check = 5,
  1710. length = value.length;
  1711. for (var i = 0; i < length; i++) {
  1712. check = (((check || 10) * 2) % 11 + parseInt(value.charAt(i), 10)) % 10;
  1713. }
  1714. return (check === 1);
  1715. },
  1716. /**
  1717. * Implements Mod 37, 36 (ISO 7064) algorithm
  1718. * Usages:
  1719. * mod37And36('A12425GABC1234002M')
  1720. * mod37And36('002006673085', '0123456789')
  1721. *
  1722. * @param {String} value
  1723. * @param {String} [alphabet]
  1724. * @returns {Boolean}
  1725. */
  1726. mod37And36: function(value, alphabet) {
  1727. alphabet = alphabet || '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  1728. var modulus = alphabet.length,
  1729. length = value.length,
  1730. check = Math.floor(modulus / 2);
  1731. for (var i = 0; i < length; i++) {
  1732. check = (((check || modulus) * 2) % (modulus + 1) + alphabet.indexOf(value.charAt(i))) % modulus;
  1733. }
  1734. return (check === 1);
  1735. }
  1736. };
  1737. }(window.jQuery));