bootstrapValidator.js 71 KB

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