bootstrapValidator.js 73 KB

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