bootstrapValidator.js 73 KB

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