bootstrapValidator.js 71 KB

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