bootstrapValidator.js 78 KB

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