bootstrapValidator.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  1. /**
  2. * BootstrapValidator (https://github.com/nghuuphuoc/bootstrapvalidator)
  3. *
  4. * A jQuery plugin to validate form fields. Use with Bootstrap 3
  5. *
  6. * @author http://twitter.com/nghuuphuoc
  7. * @copyright (c) 2013 - 2014 Nguyen Huu Phuoc
  8. * @license MIT
  9. */
  10. (function($) {
  11. var BootstrapValidator = function(form, options) {
  12. this.$form = $(form);
  13. this.options = $.extend({}, BootstrapValidator.DEFAULT_OPTIONS, options);
  14. this.$invalidField = null; // First invalid field
  15. this.$submitButton = null; // The submit button which is clicked to submit form
  16. // Validating status
  17. this.STATUS_NOT_VALIDATED = 'NOT_VALIDATED';
  18. this.STATUS_VALIDATING = 'VALIDATING';
  19. this.STATUS_INVALID = 'INVALID';
  20. this.STATUS_VALID = 'VALID';
  21. // Determine the event that is fired when user change the field value
  22. // Most modern browsers supports input event except IE 7, 8.
  23. // IE 9 supports input event but the event is still not fired if I press the backspace key.
  24. // In that case I will use the keydown event
  25. var el = document.createElement('div');
  26. this._changeEvent = ('oninput' in el) ? 'input' : 'keydown';
  27. // The flag to indicate that the form is ready to submit when a remote/callback validator returns
  28. this._submitIfValid = null;
  29. // Field elements
  30. this._cacheFields = {};
  31. this._init();
  32. };
  33. // The default options
  34. BootstrapValidator.DEFAULT_OPTIONS = {
  35. // The form CSS class
  36. elementClass: 'bootstrap-validator-form',
  37. // Default invalid message
  38. message: 'This value is not valid',
  39. // Indicate fields which won't be validated
  40. // By default, the plugin will not validate the following kind of fields:
  41. // - disabled
  42. // - hidden
  43. // - invisible
  44. //
  45. // The setting consists of jQuery filters. Accept 3 formats:
  46. // - A string. Use a comma to separate filter
  47. // - An array. Each element is a filter
  48. // - An array. Each element can be a callback function
  49. // function($field, validator) {
  50. // $field is jQuery object representing the field element
  51. // validator is the BootstrapValidator instance
  52. // return true or false;
  53. // }
  54. //
  55. // The 3 following settings are equivalent:
  56. //
  57. // 1) ':disabled, :hidden, :not(:visible)'
  58. // 2) [':disabled', ':hidden', ':not(:visible)']
  59. // 3) [':disabled', ':hidden', function($field) {
  60. // return !$field.is(':visible');
  61. // }]
  62. excluded: [':disabled', ':hidden', ':not(:visible)'],
  63. // Shows ok/error/loading icons based on the field validity.
  64. // This feature requires Bootstrap v3.1.0 or later (http://getbootstrap.com/css/#forms-control-validation).
  65. // Since Bootstrap doesn't provide any methods to know its version, this option cannot be on/off automatically.
  66. // In other word, to use this feature you have to upgrade your Bootstrap to v3.1.0 or later.
  67. //
  68. // Examples:
  69. // - Use Glyphicons icons:
  70. // feedbackIcons: {
  71. // valid: 'glyphicon glyphicon-ok',
  72. // invalid: 'glyphicon glyphicon-remove',
  73. // validating: 'glyphicon glyphicon-refresh'
  74. // }
  75. // - Use FontAwesome icons:
  76. // feedbackIcons: {
  77. // valid: 'fa fa-check',
  78. // invalid: 'fa fa-times',
  79. // validating: 'fa fa-refresh'
  80. // }
  81. feedbackIcons: {
  82. valid: null,
  83. invalid: null,
  84. validating: null
  85. },
  86. // The submit buttons selector
  87. // These buttons will be disabled to prevent the valid form from multiple submissions
  88. submitButtons: 'button[type="submit"]',
  89. // The custom submit handler
  90. // It will prevent the form from the default submission
  91. //
  92. // submitHandler: function(validator, form) {
  93. // - validator is the BootstrapValidator instance
  94. // - form is the jQuery object present the current form
  95. // }
  96. submitHandler: null,
  97. // Live validating option
  98. // Can be one of 3 values:
  99. // - enabled: The plugin validates fields as soon as they are changed
  100. // - disabled: Disable the live validating. The error messages are only shown after the form is submitted
  101. // - submitted: The live validating is enabled after the form is submitted
  102. live: 'enabled',
  103. // Map the field name with validator rules
  104. fields: null
  105. };
  106. BootstrapValidator.prototype = {
  107. constructor: BootstrapValidator,
  108. /**
  109. * Init form
  110. */
  111. _init: function() {
  112. var that = this,
  113. options = {
  114. excluded: this.$form.attr('data-bv-excluded'),
  115. trigger: this.$form.attr('data-bv-trigger'),
  116. message: this.$form.attr('data-bv-message'),
  117. submitButtons: this.$form.attr('data-bv-submitbuttons'),
  118. live: this.$form.attr('data-bv-live'),
  119. fields: {},
  120. feedbackIcons: {
  121. valid: this.$form.attr('data-bv-feedbackicons-valid'),
  122. invalid: this.$form.attr('data-bv-feedbackicons-invalid'),
  123. validating: this.$form.attr('data-bv-feedbackicons-validating')
  124. }
  125. },
  126. validator,
  127. v, // Validator name
  128. enabled,
  129. optionName,
  130. optionValue,
  131. html5AttrName,
  132. html5Attrs;
  133. this.$form
  134. // Disable client side validation in HTML 5
  135. .attr('novalidate', 'novalidate')
  136. .addClass(this.options.elementClass)
  137. // Disable the default submission first
  138. .on('submit.bv', function(e) {
  139. e.preventDefault();
  140. that.validate();
  141. })
  142. .on('click', this.options.submitButtons, function() {
  143. that.$submitButton = $(this);
  144. // The user just click the submit button
  145. that._submitIfValid = true;
  146. })
  147. // Find all fields which have either "name" or "data-bv-field" attribute
  148. .find('[name], [data-bv-field]').each(function() {
  149. var $field = $(this);
  150. // Don't initialize hidden input
  151. if ('hidden' == $field.attr('type')) {
  152. return;
  153. }
  154. var field = $field.attr('name') || $field.attr('data-bv-field');
  155. $field.attr('data-bv-field', field);
  156. options.fields[field] = $.extend({}, {
  157. trigger: $field.attr('data-bv-trigger'),
  158. message: $field.attr('data-bv-message'),
  159. container: $field.attr('data-bv-container'),
  160. selector: $field.attr('data-bv-selector'),
  161. validators: {}
  162. }, options.fields[field]);
  163. for (v in $.fn.bootstrapValidator.validators) {
  164. validator = $.fn.bootstrapValidator.validators[v];
  165. enabled = $field.attr('data-bv-' + v.toLowerCase()) + '';
  166. html5Attrs = ('function' == typeof validator.enableByHtml5) ? validator.enableByHtml5($(this)) : null;
  167. if ((html5Attrs && enabled != 'false')
  168. || (html5Attrs !== true && ('' == enabled || 'true' == enabled)))
  169. {
  170. // Try to parse the options via attributes
  171. validator.html5Attributes = validator.html5Attributes || { message: 'message' };
  172. options.fields[field]['validators'][v] = $.extend({}, html5Attrs == true ? {} : html5Attrs, options.fields[field]['validators'][v]);
  173. for (html5AttrName in validator.html5Attributes) {
  174. optionName = validator.html5Attributes[html5AttrName];
  175. optionValue = $field.attr('data-bv-' + v.toLowerCase() + '-' + html5AttrName);
  176. if (optionValue) {
  177. if ('true' == optionValue) {
  178. optionValue = true;
  179. } else if ('false' == optionValue) {
  180. optionValue = false;
  181. }
  182. options.fields[field]['validators'][v][optionName] = optionValue;
  183. }
  184. }
  185. }
  186. }
  187. });
  188. this.options = $.extend(true, this.options, options);
  189. if ('string' == typeof this.options.excluded) {
  190. this.options.excluded = $.map(this.options.excluded.split(','), function(item) {
  191. // Trim the spaces
  192. return $.trim(item);
  193. });
  194. }
  195. for (var field in this.options.fields) {
  196. this._initField(field);
  197. }
  198. },
  199. /**
  200. * Init field
  201. *
  202. * @param {String} field The field name
  203. */
  204. _initField: function(field) {
  205. if (this.options.fields[field] == null || this.options.fields[field].validators == null) {
  206. return;
  207. }
  208. var fields = this.getFieldElements(field);
  209. // We don't need to validate non-existing fields
  210. if (fields == []) {
  211. delete this.options.fields[field];
  212. return;
  213. }
  214. for (var validatorName in this.options.fields[field].validators) {
  215. if (!$.fn.bootstrapValidator.validators[validatorName]) {
  216. delete this.options.fields[field].validators[validatorName];
  217. }
  218. }
  219. if (this.options.fields[field]['enabled'] == null) {
  220. this.options.fields[field]['enabled'] = true;
  221. }
  222. for (var i = 0; i < fields.length; i++) {
  223. this._initFieldElement($(fields[i]));
  224. }
  225. },
  226. _initFieldElement: function($field) {
  227. var that = this,
  228. field = $field.attr('name') || $field.attr('data-bv-field'),
  229. fields = this.getFieldElements(field),
  230. index = fields.index($field),
  231. type = $field.attr('type'),
  232. total = fields.length,
  233. updateAll = (total == 1) || ('radio' == type) || ('checkbox' == type),
  234. $parent = $field.parents('.form-group'),
  235. // Allow user to indicate where the error messages are shown
  236. $message = this.options.fields[field].container ? $parent.find(this.options.fields[field].container) : this._getMessageContainer($field);
  237. // Remove all error messages and feedback icons
  238. $message.find('.help-block[data-bv-validator]').remove();
  239. $parent.find('i[data-bv-field]').remove();
  240. // Set the attribute to indicate the fields which are defined by selector
  241. if (!$field.attr('data-bv-field')) {
  242. $field.attr('data-bv-field', field);
  243. }
  244. // Whenever the user change the field value, mark it as not validated yet
  245. var event = ('radio' == type || 'checkbox' == type || 'file' == type || 'SELECT' == $field.get(0).tagName) ? 'change' : this._changeEvent;
  246. $field.off(event + '.update.bv').on(event + '.update.bv', function() {
  247. // Reset the flag
  248. that._submitIfValid = false;
  249. that.updateElementStatus($(this), that.STATUS_NOT_VALIDATED);
  250. });
  251. // Create help block elements for showing the error messages
  252. $field.data('bv.messages', $message);
  253. for (var validatorName in this.options.fields[field].validators) {
  254. $field.data('bv.result.' + validatorName, this.STATUS_NOT_VALIDATED);
  255. if (!updateAll || index == total - 1) {
  256. $('<small/>')
  257. .css('display', 'none')
  258. .attr('data-bv-validator', validatorName)
  259. .html(this.options.fields[field].validators[validatorName].message || this.options.fields[field].message || this.options.message)
  260. .addClass('help-block')
  261. .appendTo($message);
  262. }
  263. }
  264. // Prepare the feedback icons
  265. // Available from Bootstrap 3.1 (http://getbootstrap.com/css/#forms-control-validation)
  266. if (this.options.feedbackIcons
  267. && this.options.feedbackIcons.validating && this.options.feedbackIcons.invalid && this.options.feedbackIcons.valid
  268. && (!updateAll || index == total - 1))
  269. {
  270. $parent.removeClass('has-success').removeClass('has-error').addClass('has-feedback');
  271. var $icon = $('<i/>').css('display', 'none').addClass('form-control-feedback').attr('data-bv-field', field).insertAfter($field);
  272. // The feedback icon does not render correctly if there is no label
  273. // https://github.com/twbs/bootstrap/issues/12873
  274. if ($parent.find('label').length == 0) {
  275. $icon.css('top', 0);
  276. }
  277. }
  278. // Set live mode
  279. var trigger = this.options.fields[field].trigger || this.options.trigger || event,
  280. events = $.map(trigger.split(' '), function(item) {
  281. return item + '.live.bv';
  282. }).join(' ');
  283. switch (this.options.live) {
  284. case 'submitted':
  285. break;
  286. case 'disabled':
  287. $field.off(events);
  288. break;
  289. case 'enabled':
  290. default:
  291. $field.off(events).on(events, function() {
  292. that.validateFieldElement($(this));
  293. });
  294. break;
  295. }
  296. },
  297. /**
  298. * Get the element to place the error messages
  299. *
  300. * @param {jQuery} $field The field element
  301. * @returns {jQuery}
  302. */
  303. _getMessageContainer: function($field) {
  304. var $parent = $field.parent();
  305. if ($parent.hasClass('form-group')) {
  306. return $parent;
  307. }
  308. var cssClasses = $parent.attr('class');
  309. if (!cssClasses) {
  310. return this._getMessageContainer($parent);
  311. }
  312. cssClasses = cssClasses.split(' ');
  313. var n = cssClasses.length;
  314. for (var i = 0; i < n; i++) {
  315. if (/^col-(xs|sm|md|lg)-\d+$/.test(cssClasses[i]) || /^col-(xs|sm|md|lg)-offset-\d+$/.test(cssClasses[i])) {
  316. return $parent;
  317. }
  318. }
  319. return this._getMessageContainer($parent);
  320. },
  321. /**
  322. * Called when all validations are completed
  323. */
  324. _submit: function() {
  325. var isValid = this.isValid(),
  326. eventType = isValid ? 'success.form.bv' : 'error.form.bv',
  327. e = $.Event(eventType);
  328. this.$form.trigger(e);
  329. // Call default handler
  330. // Check if whether the submit button is clicked
  331. if (this.$submitButton) {
  332. isValid ? this._onSuccess(e) : this._onError(e);
  333. }
  334. },
  335. /**
  336. * Check if the field is excluded.
  337. * Returning true means that the field will not be validated
  338. *
  339. * @param {jQuery} $field The field element
  340. * @return {Boolean}
  341. */
  342. _isExcluded: function($field) {
  343. if (this.options.excluded) {
  344. for (var i in this.options.excluded) {
  345. if (('string' == typeof this.options.excluded[i] && $field.is(this.options.excluded[i]))
  346. || ('function' == typeof this.options.excluded[i] && this.options.excluded[i].call(this, $field, this) == true))
  347. {
  348. return true;
  349. }
  350. }
  351. }
  352. return false;
  353. },
  354. // --- Events ---
  355. /**
  356. * The default handler of error.form.bv event.
  357. * It will be called when there is a invalid field
  358. *
  359. * @param {jQuery.Event} e The jQuery event object
  360. */
  361. _onError: function(e) {
  362. if (e.isDefaultPrevented()) {
  363. return;
  364. }
  365. if ('submitted' == this.options.live) {
  366. // Enable live mode
  367. this.options.live = 'enabled';
  368. var that = this;
  369. for (var field in this.options.fields) {
  370. (function(f) {
  371. var fields = that.getFieldElements(f);
  372. if (fields.length) {
  373. var type = $(fields[0]).attr('type'),
  374. event = ('radio' == type || 'checkbox' == type || 'file' == type || 'SELECT' == $(fields[0]).get(0).tagName) ? 'change' : that._changeEvent,
  375. trigger = that.options.fields[field].trigger || that.options.trigger || event,
  376. events = $.map(trigger.split(' '), function(item) {
  377. return item + '.live.bv';
  378. }).join(' ');
  379. for (var i = 0; i < fields.length; i++) {
  380. $(fields[i]).off(events).on(events, function() {
  381. that.validateFieldElement($(this));
  382. });
  383. }
  384. }
  385. })(field);
  386. }
  387. }
  388. // Focus to the first invalid field
  389. if (this.$invalidField) {
  390. // Activate the tab containing the invalid field if exists
  391. var $tab = this.$invalidField.parents('.tab-pane'),
  392. tabId;
  393. if ($tab && (tabId = $tab.attr('id'))) {
  394. $('a[href="#' + tabId + '"][data-toggle="tab"]').trigger('click.bs.tab.data-api');
  395. }
  396. this.$invalidField.focus();
  397. }
  398. },
  399. /**
  400. * The default handler of success.form.bv event.
  401. * It will be called when all the fields are valid
  402. *
  403. * @param {jQuery.Event} e The jQuery event object
  404. */
  405. _onSuccess: function(e) {
  406. if (e.isDefaultPrevented()) {
  407. return;
  408. }
  409. // Call the custom submission if enabled
  410. if (this.options.submitHandler && 'function' == typeof this.options.submitHandler) {
  411. // If you want to submit the form inside your submit handler, please call defaultSubmit() method
  412. this.options.submitHandler.call(this, this, this.$form, this.$submitButton);
  413. } else {
  414. this.disableSubmitButtons(true).defaultSubmit();
  415. }
  416. },
  417. // --- Public methods ---
  418. /**
  419. * Retrieve the field elements by given name
  420. *
  421. * @param {String} field The field name
  422. * @returns {null|jQuery[]}
  423. */
  424. getFieldElements: function(field) {
  425. if (!this._cacheFields[field]) {
  426. this._cacheFields[field] = this.options.fields[field].selector
  427. ? $(this.options.fields[field].selector)
  428. : this.$form.find('[name="' + field + '"]');
  429. }
  430. return this._cacheFields[field];
  431. },
  432. /**
  433. * Disable/enable submit buttons
  434. *
  435. * @param {Boolean} disabled Can be true or false
  436. * @returns {BootstrapValidator}
  437. */
  438. disableSubmitButtons: function(disabled) {
  439. if (!disabled) {
  440. this.$form.find(this.options.submitButtons).removeAttr('disabled');
  441. } else if (this.options.live != 'disabled') {
  442. // Don't disable if the live validating mode is disabled
  443. this.$form.find(this.options.submitButtons).attr('disabled', 'disabled');
  444. }
  445. return this;
  446. },
  447. /**
  448. * Validate the form
  449. *
  450. * @return {BootstrapValidator}
  451. */
  452. validate: function() {
  453. if (!this.options.fields) {
  454. return this;
  455. }
  456. this.disableSubmitButtons(true);
  457. for (var field in this.options.fields) {
  458. this.validateField(field);
  459. }
  460. this._submit();
  461. return this;
  462. },
  463. /**
  464. * Validate given field
  465. *
  466. * @param {String} field The field name
  467. * @returns {BootstrapValidator}
  468. */
  469. validateField: function(field) {
  470. var fields = this.getFieldElements(field),
  471. type = fields.attr('type'),
  472. n = (('radio' == type) || ('checkbox' == type)) ? 1 : fields.length;
  473. for (var i = 0; i < n; i++) {
  474. this.validateFieldElement($(fields[i]));
  475. }
  476. return this;
  477. },
  478. /**
  479. * Validate field element
  480. *
  481. * @param {jQuery} $field The field element
  482. * @returns {BootstrapValidator}
  483. */
  484. validateFieldElement: function($field) {
  485. var that = this,
  486. field = $field.attr('data-bv-field'),
  487. fields = this.getFieldElements(field),
  488. type = $field.attr('type'),
  489. updateAll = (fields && fields.length == 1) || ('radio' == type) || ('checkbox' == type),
  490. validators = this.options.fields[field].validators,
  491. validatorName,
  492. validateResult;
  493. if (!this.options.fields[field]['enabled'] || this._isExcluded($field)) {
  494. return this;
  495. }
  496. for (validatorName in validators) {
  497. if ($field.data('bv.dfs.' + validatorName)) {
  498. $field.data('bv.dfs.' + validatorName).reject();
  499. }
  500. // Don't validate field if it is already done
  501. var result = $field.data('bv.result.' + validatorName);
  502. if (result == this.STATUS_VALID || result == this.STATUS_INVALID) {
  503. continue;
  504. }
  505. $field.data('bv.result.' + validatorName, this.STATUS_VALIDATING);
  506. validateResult = $.fn.bootstrapValidator.validators[validatorName].validate(this, $field, validators[validatorName]);
  507. if ('object' == typeof validateResult) {
  508. updateAll ? this.updateStatus(field, this.STATUS_VALIDATING, validatorName)
  509. : this.updateElementStatus($field, this.STATUS_VALIDATING, validatorName);
  510. $field.data('bv.dfs.' + validatorName, validateResult);
  511. validateResult.done(function($f, v, isValid) {
  512. // v is validator name
  513. $f.removeData('bv.dfs.' + v);
  514. updateAll ? that.updateStatus($f.attr('data-bv-field'), isValid ? that.STATUS_VALID : that.STATUS_INVALID, v)
  515. : that.updateElementStatus($f, isValid ? that.STATUS_VALID : that.STATUS_INVALID, v);
  516. if (isValid && that._submitIfValid == true) {
  517. // If a remote validator returns true and the form is ready to submit, then do it
  518. that._submit();
  519. }
  520. });
  521. } else if ('boolean' == typeof validateResult) {
  522. updateAll ? this.updateStatus(field, validateResult ? this.STATUS_VALID : this.STATUS_INVALID, validatorName)
  523. : this.updateElementStatus($field, validateResult ? this.STATUS_VALID : this.STATUS_INVALID, validatorName);
  524. }
  525. }
  526. return this;
  527. },
  528. /**
  529. * Update all validating results of elements which have the same field name
  530. *
  531. * @param {String} field The field name
  532. * @param {String} status The status. Can be 'NOT_VALIDATED', 'VALIDATING', 'INVALID' or 'VALID'
  533. * @param {String} [validatorName] The validator name. If null, the method updates validity result for all validators
  534. * @return {BootstrapValidator}
  535. */
  536. updateStatus: function(field, status, validatorName) {
  537. var fields = this.getFieldElements(field),
  538. type = fields.attr('type'),
  539. n = (('radio' == type) || ('checkbox' == type)) ? 1 : fields.length;
  540. for (var i = 0; i < n; i++) {
  541. this.updateElementStatus($(fields[i]), status, validatorName);
  542. }
  543. return this;
  544. },
  545. /**
  546. * Update validating result of given element
  547. *
  548. * @param {jQuery} $field The field element
  549. * @param {String} status The status. Can be 'NOT_VALIDATED', 'VALIDATING', 'INVALID' or 'VALID'
  550. * @param {String} [validatorName] The validator name. If null, the method updates validity result for all validators
  551. * @return {BootstrapValidator}
  552. */
  553. updateElementStatus: function($field, status, validatorName) {
  554. var that = this,
  555. field = $field.attr('data-bv-field'),
  556. $parent = $field.parents('.form-group'),
  557. $message = $field.data('bv.messages'),
  558. $rowErrors = $parent.find('.help-block[data-bv-validator]'),
  559. $errors = $message.find('.help-block[data-bv-validator]'),
  560. $icon = $parent.find('.form-control-feedback[data-bv-field="' + field + '"]');
  561. // Update status
  562. if (validatorName) {
  563. $field.data('bv.result.' + validatorName, status);
  564. } else {
  565. for (var v in this.options.fields[field].validators) {
  566. $field.data('bv.result.' + v, status);
  567. }
  568. }
  569. // Show/hide error elements and feedback icons
  570. switch (status) {
  571. case this.STATUS_VALIDATING:
  572. this.disableSubmitButtons(true);
  573. $parent.removeClass('has-success').removeClass('has-error');
  574. // TODO: Show validating message
  575. validatorName ? $errors.filter('.help-block[data-bv-validator="' + validatorName + '"]').hide() : $errors.hide();
  576. if ($icon) {
  577. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).addClass(this.options.feedbackIcons.validating).show();
  578. }
  579. break;
  580. case this.STATUS_INVALID:
  581. this.disableSubmitButtons(true);
  582. $parent.removeClass('has-success').addClass('has-error');
  583. validatorName ? $errors.filter('[data-bv-validator="' + validatorName + '"]').show() : $errors.show();
  584. if ($icon) {
  585. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.validating).addClass(this.options.feedbackIcons.invalid).show();
  586. }
  587. break;
  588. case this.STATUS_VALID:
  589. validatorName ? $errors.filter('[data-bv-validator="' + validatorName + '"]').hide() : $errors.hide();
  590. // If the field is valid (passes all validators)
  591. var validField = ($errors.filter(function() {
  592. var display = $(this).css('display'), v = $(this).attr('data-bv-validator');
  593. return ('block' == display) || ($field.data('bv.result.' + v) != that.STATUS_VALID);
  594. }).length == 0);
  595. this.disableSubmitButtons(validField ? false : true);
  596. if ($icon) {
  597. $icon
  598. .removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).removeClass(this.options.feedbackIcons.valid)
  599. .addClass(validField ? this.options.feedbackIcons.valid : this.options.feedbackIcons.invalid)
  600. .show();
  601. }
  602. // Check if all fields in the same row are valid
  603. var validRow = ($rowErrors.filter(function() {
  604. var display = $(this).css('display'), v = $(this).attr('data-bv-validator');
  605. return ('block' == display) || ($field.data('bv.result.' + v) != that.STATUS_VALID);
  606. }).length == 0);
  607. $parent.removeClass('has-error has-success').addClass(validRow ? 'has-success' : 'has-error');
  608. break;
  609. case this.STATUS_NOT_VALIDATED:
  610. default:
  611. this.disableSubmitButtons(false);
  612. $parent.removeClass('has-success').removeClass('has-error');
  613. validatorName ? $errors.filter('.help-block[data-bv-validator="' + validatorName + '"]').hide() : $errors.hide();
  614. if ($icon) {
  615. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).hide();
  616. }
  617. break;
  618. }
  619. return this;
  620. },
  621. /**
  622. * Check the form validity
  623. *
  624. * @returns {Boolean}
  625. */
  626. isValid: function() {
  627. var fields, field, $field,
  628. type, status, validatorName,
  629. n, i;
  630. for (field in this.options.fields) {
  631. if (this.options.fields[field] == null || !this.options.fields[field]['enabled']) {
  632. continue;
  633. }
  634. fields = this.getFieldElements(field);
  635. type = fields.attr('type');
  636. n = (('radio' == type) || ('checkbox' == type)) ? 1 : fields.length;
  637. for (i = 0; i < n; i++) {
  638. $field = $(fields[i]);
  639. if (this._isExcluded($field)) {
  640. continue;
  641. }
  642. for (validatorName in this.options.fields[field].validators) {
  643. status = $field.data('bv.result.' + validatorName);
  644. if (status == this.STATUS_NOT_VALIDATED || status == this.STATUS_VALIDATING) {
  645. return false;
  646. }
  647. if (status == this.STATUS_INVALID) {
  648. this.$invalidField = $field;
  649. return false;
  650. }
  651. }
  652. }
  653. }
  654. return true;
  655. },
  656. /**
  657. * Submit the form using default submission.
  658. * It also does not perform any validations when submitting the form
  659. *
  660. * It might be used when you want to submit the form right inside the submitHandler()
  661. */
  662. defaultSubmit: function() {
  663. this.$form.off('submit.bv').submit();
  664. },
  665. // Useful APIs which aren't used internally
  666. /**
  667. * Add new field element
  668. *
  669. * @param {jQuery} $field The field element
  670. * @param {Object} options The field options
  671. * @returns {BootstrapValidator}
  672. */
  673. addFieldElement: function($field, options) {
  674. var field = $field.attr('name') || $field.attr('data-bv-field'),
  675. type = $field.attr('type'),
  676. isNewField = !this._cacheFields[field];
  677. // Update cache
  678. if (!isNewField && this._cacheFields[field].index($field) == -1) {
  679. this._cacheFields[field] = this._cacheFields[field].add($field);
  680. }
  681. if ('checkbox' == type || 'radio' == type || isNewField) {
  682. this._initField(field);
  683. } else {
  684. this._initFieldElement($field);
  685. }
  686. return this;
  687. },
  688. /**
  689. * Remove given field element
  690. *
  691. * @param {jQuery} $field The field element
  692. * @returns {BootstrapValidator}
  693. */
  694. removeFieldElement: function($field) {
  695. var field = $field.attr('name') || $field.attr('data-bv-field'),
  696. type = $field.attr('type'),
  697. index = this._cacheFields[field].index($field);
  698. (index == -1) ? (delete this._cacheFields[field]) : this._cacheFields[field].splice(index, 1);
  699. if ('checkbox' == type || 'radio' == type) {
  700. this._initField(field);
  701. }
  702. return this;
  703. },
  704. /**
  705. * Reset the form
  706. *
  707. * @param {Boolean} resetFormData Reset current form data
  708. * @return {BootstrapValidator}
  709. */
  710. resetForm: function(resetFormData) {
  711. var field, fields, total, type, validator;
  712. for (field in this.options.fields) {
  713. fields = this.getFieldElements(field);
  714. total = fields.length;
  715. for (var i = 0; i < total; i++) {
  716. for (validator in this.options.fields[field].validators) {
  717. $(fields[i]).removeData('bv.dfs.' + validator);
  718. }
  719. }
  720. // Mark field as not validated yet
  721. this.updateStatus(field, this.STATUS_NOT_VALIDATED);
  722. if (resetFormData) {
  723. type = fields.attr('type');
  724. ('radio' == type || 'checkbox' == type) ? fields.removeAttr('checked').removeAttr('selected') : fields.val('');
  725. }
  726. }
  727. this.$invalidField = null;
  728. this.$submitButton = null;
  729. // Enable submit buttons
  730. this.disableSubmitButtons(false);
  731. return this;
  732. },
  733. /**
  734. * Enable/Disable all validators to given field
  735. *
  736. * @param {String} field The field name
  737. * @param {Boolean} enabled Enable/Disable field validators
  738. * @return {BootstrapValidator}
  739. */
  740. enableFieldValidators: function(field, enabled) {
  741. this.options.fields[field]['enabled'] = enabled;
  742. this.updateStatus(field, this.STATUS_NOT_VALIDATED);
  743. return this;
  744. }
  745. };
  746. // Plugin definition
  747. $.fn.bootstrapValidator = function(option, params) {
  748. return this.each(function() {
  749. var $this = $(this),
  750. data = $this.data('bootstrapValidator'),
  751. options = 'object' == typeof option && option;
  752. if (!data) {
  753. data = new BootstrapValidator(this, options);
  754. $this.data('bootstrapValidator', data);
  755. }
  756. // Allow to call plugin method
  757. if ('string' == typeof option) {
  758. data[option](params);
  759. }
  760. });
  761. };
  762. // Available validators
  763. $.fn.bootstrapValidator.validators = {};
  764. $.fn.bootstrapValidator.Constructor = BootstrapValidator;
  765. // Helper methods, which can be used in validator class
  766. $.fn.bootstrapValidator.helpers = {
  767. /**
  768. * Implement Luhn validation algorithm ((http://en.wikipedia.org/wiki/Luhn))
  769. * Credit to https://gist.github.com/ShirtlessKirk/2134376
  770. *
  771. * @param {String} value
  772. * @returns {boolean}
  773. */
  774. luhn: function(value) {
  775. var length = value.length,
  776. mul = 0,
  777. prodArr = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]],
  778. sum = 0;
  779. while (length--) {
  780. sum += prodArr[mul][parseInt(value.charAt(length), 10)];
  781. mul ^= 1;
  782. }
  783. return (sum % 10 === 0 && sum > 0);
  784. }
  785. };
  786. }(window.jQuery));