bootstrapValidator.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  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.dfds = {}; // Array of deferred
  15. this.results = {}; // Validating results
  16. this.invalidField = null; // First invalid field
  17. this.$submitButton = null; // The submit button which is clicked to submit form
  18. this._init();
  19. this.STATUS_NOT_VALIDATED = 'NOT_VALIDATED';
  20. this.STATUS_VALIDATING = 'VALIDATING';
  21. this.STATUS_INVALID = 'INVALID';
  22. this.STATUS_VALID = 'VALID';
  23. };
  24. // The default options
  25. BootstrapValidator.DEFAULT_OPTIONS = {
  26. // The form CSS class
  27. elementClass: 'bootstrap-validator-form',
  28. // Default invalid message
  29. message: 'This value is not valid',
  30. // Shows ok/error/loading icons based on the field validity.
  31. // This feature requires Bootstrap v3.1.0 or later (http://getbootstrap.com/css/#forms-control-validation).
  32. // Since Bootstrap doesn't provide any methods to know its version, this option cannot be on/off automatically.
  33. // In other word, to use this feature you have to upgrade your Bootstrap to v3.1.0 or later.
  34. //
  35. // Examples:
  36. // - Use Glyphicons icons:
  37. // feedbackIcons: {
  38. // valid: 'glyphicon glyphicon-ok',
  39. // invalid: 'glyphicon glyphicon-remove',
  40. // validating: 'glyphicon glyphicon-refresh'
  41. // }
  42. // - Use FontAwesome icons:
  43. // feedbackIcons: {
  44. // valid: 'fa fa-check',
  45. // invalid: 'fa fa-times',
  46. // validating: 'fa fa-refresh'
  47. // }
  48. feedbackIcons: {
  49. valid: null,
  50. invalid: null,
  51. validating: null
  52. },
  53. // The submit buttons selector
  54. // These buttons will be disabled to prevent the valid form from multiple submissions
  55. submitButtons: 'button[type="submit"]',
  56. // The custom submit handler
  57. // It will prevent the form from the default submission
  58. //
  59. // submitHandler: function(validator, form) {
  60. // - validator is the BootstrapValidator instance
  61. // - form is the jQuery object present the current form
  62. // }
  63. submitHandler: null,
  64. // Live validating option
  65. // Can be one of 3 values:
  66. // - enabled: The plugin validates fields as soon as they are changed
  67. // - disabled: Disable the live validating. The error messages are only shown after the form is submitted
  68. // - submitted: The live validating is enabled after the form is submitted
  69. live: 'enabled',
  70. // Map the field name with validator rules
  71. fields: null
  72. };
  73. BootstrapValidator.prototype = {
  74. constructor: BootstrapValidator,
  75. /**
  76. * Init form
  77. */
  78. _init: function() {
  79. var that = this,
  80. options = {
  81. trigger: this.$form.attr('data-bv-trigger'),
  82. message: this.$form.attr('data-bv-message'),
  83. submitButtons: this.$form.attr('data-bv-submitbuttons'),
  84. live: this.$form.attr('data-bv-live'),
  85. fields: {},
  86. feedbackIcons: {
  87. valid: this.$form.attr('data-bv-feedbackicons-valid'),
  88. invalid: this.$form.attr('data-bv-feedbackicons-invalid'),
  89. validating: this.$form.attr('data-bv-feedbackicons-validating')
  90. }
  91. },
  92. validator,
  93. i = 0,
  94. v, // Validator name
  95. enabled,
  96. optionName,
  97. optionValue,
  98. html5Attrs;
  99. this.$form
  100. // Disable client side validation in HTML 5
  101. .attr('novalidate', 'novalidate')
  102. .addClass(this.options.elementClass)
  103. // Disable the default submission first
  104. .on('submit.bootstrapValidator', function(e) {
  105. e.preventDefault();
  106. that.validate();
  107. })
  108. .on('click', this.options.submitButtons, function() {
  109. that.$submitButton = $(this);
  110. })
  111. // Find all fields which have either "name" or "data-bv-field" attribute
  112. .find('[name], [data-bv-field]').each(function() {
  113. var $field = $(this),
  114. field = $field.attr('name') || $field.attr('data-bv-field');
  115. $field.attr('data-bv-field', field);
  116. options.fields[field] = $.extend({}, {
  117. trigger: $field.attr('data-bv-trigger'),
  118. message: $field.attr('data-bv-message'),
  119. container: $field.attr('data-bv-container'),
  120. selector: $field.attr('data-bv-selector'),
  121. validators: {}
  122. }, options.fields[field]);
  123. for (v in $.fn.bootstrapValidator.validators) {
  124. validator = $.fn.bootstrapValidator.validators[v];
  125. enabled = $field.attr('data-bv-' + v.toLowerCase()) + '';
  126. html5Attrs = {};
  127. if (('function' == typeof validator.enableByHtml5
  128. && (html5Attrs = validator.enableByHtml5($(this)))
  129. && (enabled != 'false'))
  130. || ('undefined' == typeof validator.enableByHtml5 && ('' == enabled || 'true' == enabled)))
  131. {
  132. // Try to parse the options via attributes
  133. validator.html5Attributes = validator.html5Attributes || ['message'];
  134. options.fields[field]['validators'][v] = $.extend({}, html5Attrs == true ? {} : html5Attrs, options.fields[field]['validators'][v]);
  135. for (i in validator.html5Attributes) {
  136. optionName = validator.html5Attributes[i];
  137. optionValue = $field.attr('data-bv-' + v.toLowerCase() + '-' + optionName.toLowerCase());
  138. if (optionValue) {
  139. if ('true' == optionValue) {
  140. optionValue = true;
  141. } else if ('false' == optionValue) {
  142. optionValue = false;
  143. }
  144. options.fields[field]['validators'][v][optionName] = optionValue;
  145. }
  146. }
  147. }
  148. }
  149. });
  150. this.options = $.extend(true, this.options, options);
  151. //console.log(this.options);
  152. for (var field in this.options.fields) {
  153. this._initField(field);
  154. }
  155. this._setLiveValidating();
  156. },
  157. /**
  158. * Init field
  159. *
  160. * @param {String} field The field name
  161. */
  162. _initField: function(field) {
  163. if (this.options.fields[field] == null || this.options.fields[field].validators == null) {
  164. return;
  165. }
  166. this.dfds[field] = {};
  167. this.results[field] = {};
  168. var fields = this.getFieldElements(field);
  169. // We don't need to validate non-existing fields
  170. if (fields == null) {
  171. delete this.options.fields[field];
  172. delete this.dfds[field];
  173. return;
  174. }
  175. fields.attr('data-bv-field', field);
  176. // Create help block elements for showing the error messages
  177. var $field = $(fields[0]),
  178. $parent = $field.parents('.form-group'),
  179. // Allow user to indicate where the error messages are shown
  180. $message = this.options.fields[field].container ? $parent.find(this.options.fields[field].container) : this._getMessageContainer($field);
  181. $field.data('bootstrapValidator.messageContainer', $message);
  182. for (var validatorName in this.options.fields[field].validators) {
  183. if (!$.fn.bootstrapValidator.validators[validatorName]) {
  184. delete this.options.fields[field].validators[validatorName];
  185. continue;
  186. }
  187. this.results[field][validatorName] = this.STATUS_NOT_VALIDATED;
  188. $('<small/>')
  189. .css('display', 'none')
  190. .attr('data-bv-validator', validatorName)
  191. .html(this.options.fields[field].validators[validatorName].message || this.options.fields[field].message || this.options.message)
  192. .addClass('help-block')
  193. .appendTo($message);
  194. }
  195. // Prepare the feedback icons
  196. // Available from Bootstrap 3.1 (http://getbootstrap.com/css/#forms-control-validation)
  197. if (this.options.feedbackIcons
  198. && this.options.feedbackIcons.validating && this.options.feedbackIcons.invalid && this.options.feedbackIcons.valid)
  199. {
  200. $parent.addClass('has-feedback');
  201. var $icon = $('<i/>').css('display', 'none').addClass('form-control-feedback').attr('data-bv-field', field).insertAfter($(fields[fields.length - 1]));
  202. // The feedback icon does not render correctly if there is no label
  203. // https://github.com/twbs/bootstrap/issues/12873
  204. if ($parent.find('label').length == 0) {
  205. $icon.css('top', 0);
  206. }
  207. }
  208. if (this.options.fields[field]['enabled'] == null) {
  209. this.options.fields[field]['enabled'] = true;
  210. }
  211. // Whenever the user change the field value, mark it as not validated yet
  212. var that = this,
  213. type = fields.attr('type'),
  214. event = ('radio' == type || 'checkbox' == type || 'file' == type || 'SELECT' == fields[0].tagName) ? 'change' : 'keyup';
  215. fields.on(event + '.bootstrapValidator', function() {
  216. that.updateStatus($field, that.STATUS_NOT_VALIDATED, null);
  217. });
  218. },
  219. /**
  220. * Get the element to place the error messages
  221. *
  222. * @param {jQuery} $field The field element
  223. * @returns {jQuery}
  224. */
  225. _getMessageContainer: function($field) {
  226. var $parent = $field.parent();
  227. if ($parent.hasClass('form-group')) {
  228. return $parent;
  229. }
  230. var cssClasses = $parent.attr('class');
  231. if (!cssClasses) {
  232. return this._getMessageContainer($parent);
  233. }
  234. cssClasses = cssClasses.split(' ');
  235. var n = cssClasses.length;
  236. for (var i = 0; i < n; i++) {
  237. if (/^col-(xs|sm|md|lg)-\d+$/.test(cssClasses[i]) || /^col-(xs|sm|md|lg)-offset-\d+$/.test(cssClasses[i])) {
  238. return $parent;
  239. }
  240. }
  241. return this._getMessageContainer($parent);
  242. },
  243. /**
  244. * Enable live validating
  245. */
  246. _setLiveValidating: function() {
  247. if ('enabled' == this.options.live) {
  248. var that = this;
  249. for (var field in this.options.fields) {
  250. (function(f) {
  251. var fields = that.getFieldElements(f);
  252. if (fields) {
  253. var type = fields.attr('type'),
  254. trigger = that.options.fields[field].trigger
  255. || that.options.trigger
  256. || (('radio' == type || 'checkbox' == type || 'file' == type || 'SELECT' == fields[0].tagName) ? 'change' : 'keyup'),
  257. events = trigger.split(' ').map(function(item) {
  258. return item + '.bootstrapValidator';
  259. }).join(' ');
  260. fields.on(events, function() {
  261. that.validateField(f);
  262. });
  263. }
  264. })(field);
  265. }
  266. }
  267. },
  268. /**
  269. * Disable/Enable submit buttons
  270. *
  271. * @param {Boolean} disabled
  272. */
  273. _disableSubmitButtons: function(disabled) {
  274. if (!disabled) {
  275. this.$form.find(this.options.submitButtons).removeAttr('disabled');
  276. } else if (this.options.live != 'disabled') {
  277. // Don't disable if the live validating mode is disabled
  278. this.$form.find(this.options.submitButtons).attr('disabled', 'disabled');
  279. }
  280. },
  281. /**
  282. * Called when all validations are completed
  283. */
  284. _submit: function() {
  285. if (!this.isValid()) {
  286. if ('submitted' == this.options.live) {
  287. this.options.live = 'enabled';
  288. this._setLiveValidating();
  289. }
  290. // Focus to the first invalid field
  291. if (this.invalidField) {
  292. this.getFieldElements(this.invalidField).focus();
  293. }
  294. return;
  295. }
  296. this._disableSubmitButtons(true);
  297. // Call the custom submission if enabled
  298. if (this.options.submitHandler && 'function' == typeof this.options.submitHandler) {
  299. // Turn off the submit handler, so user can call form.submit() inside their submitHandler method
  300. this.$form.off('submit.bootstrapValidator');
  301. this.options.submitHandler.call(this, this, this.$form, this.$submitButton);
  302. } else {
  303. // Submit form
  304. this.$form.off('submit.bootstrapValidator').submit();
  305. }
  306. },
  307. // --- Public methods ---
  308. /**
  309. * Retrieve the field elements by given name
  310. *
  311. * @param {String} field The field name
  312. * @returns {null|jQuery[]}
  313. */
  314. getFieldElements: function(field) {
  315. var fields = this.$form.find(this.options.fields[field].selector || '[name="' + field + '"]');
  316. return (fields.length == 0) ? null : fields;
  317. },
  318. /**
  319. * Validate the form
  320. *
  321. * @return {BootstrapValidator}
  322. */
  323. validate: function() {
  324. if (!this.options.fields) {
  325. return this;
  326. }
  327. this._disableSubmitButtons(true);
  328. for (var field in this.options.fields) {
  329. this.validateField(field);
  330. }
  331. this._submit();
  332. return this;
  333. },
  334. /**
  335. * Validate given field
  336. *
  337. * @param {String} field The field name
  338. */
  339. validateField: function(field) {
  340. if (!this.options.fields[field]['enabled']) {
  341. return;
  342. }
  343. var that = this,
  344. fields = this.getFieldElements(field),
  345. $field = $(fields[0]),
  346. validators = this.options.fields[field].validators,
  347. validatorName,
  348. validateResult;
  349. // We don't need to validate disabled field
  350. if (fields.length == 1 && fields.is(':disabled')) {
  351. delete this.options.fields[field];
  352. delete this.dfds[field];
  353. return;
  354. }
  355. for (validatorName in validators) {
  356. if (this.dfds[field][validatorName]) {
  357. this.dfds[field][validatorName].reject();
  358. }
  359. // Don't validate field if it is already done
  360. if (this.results[field][validatorName] == this.STATUS_VALID || this.results[field][validatorName] == this.STATUS_INVALID) {
  361. continue;
  362. }
  363. this.results[field][validatorName] = this.STATUS_VALIDATING;
  364. validateResult = $.fn.bootstrapValidator.validators[validatorName].validate(this, $field, validators[validatorName]);
  365. if ('object' == typeof validateResult) {
  366. this.updateStatus($field, this.STATUS_VALIDATING, validatorName);
  367. this.dfds[field][validatorName] = validateResult;
  368. validateResult.done(function(isValid, v) {
  369. // v is validator name
  370. delete that.dfds[field][v];
  371. that.updateStatus($field, isValid ? that.STATUS_VALID : that.STATUS_INVALID, v);
  372. if (isValid && 'disabled' == that.options.live) {
  373. that._submit();
  374. }
  375. });
  376. } else if ('boolean' == typeof validateResult) {
  377. this.updateStatus($field, validateResult ? this.STATUS_VALID : this.STATUS_INVALID, validatorName);
  378. }
  379. }
  380. },
  381. /**
  382. * Check the form validity
  383. *
  384. * @returns {Boolean}
  385. */
  386. isValid: function() {
  387. var field, validatorName;
  388. for (field in this.results) {
  389. if (this.options.fields[field] == null || !this.options.fields[field]['enabled']) {
  390. continue;
  391. }
  392. for (validatorName in this.results[field]) {
  393. if (this.results[field][validatorName] == this.STATUS_NOT_VALIDATED || this.results[field][validatorName] == this.STATUS_VALIDATING) {
  394. return false;
  395. }
  396. if (this.results[field][validatorName] == this.STATUS_INVALID) {
  397. this.invalidField = field;
  398. return false;
  399. }
  400. }
  401. }
  402. return true;
  403. },
  404. /**
  405. * Update field status
  406. *
  407. * @param {String|jQuery} field The field name or field element
  408. * @param {String} status The status
  409. * Can be 'NOT_VALIDATED', 'VALIDATING', 'INVALID' or 'VALID'
  410. * @param {String|null} validatorName The validator name. If null, the method updates validity result for all validators
  411. * @return {BootstrapValidator}
  412. */
  413. updateStatus: function(field, status, validatorName) {
  414. var $field = ('string' == typeof field) ? this.getFieldElements(field) : field,
  415. that = this,
  416. field = $field.attr('data-bv-field'),
  417. $parent = $field.parents('.form-group'),
  418. $message = $field.data('bootstrapValidator.messageContainer'),
  419. $errors = $message.find('.help-block[data-bv-validator]'),
  420. $icon = $parent.find('.form-control-feedback[data-bv-field="' + field + '"]');
  421. // Update status
  422. if (validatorName) {
  423. this.results[field][validatorName] = status;
  424. } else {
  425. for (var v in this.options.fields[field].validators) {
  426. this.results[field][v] = status;
  427. }
  428. }
  429. // Show/hide error elements and feedback icons
  430. switch (status) {
  431. case this.STATUS_VALIDATING:
  432. this._disableSubmitButtons(true);
  433. $parent.removeClass('has-success').removeClass('has-error');
  434. // TODO: Show validating message
  435. validatorName ? $errors.filter('.help-block[data-bv-validator="' + validatorName + '"]').hide() : $errors.hide();
  436. if ($icon) {
  437. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).addClass(this.options.feedbackIcons.validating).show();
  438. }
  439. break;
  440. case this.STATUS_INVALID:
  441. this._disableSubmitButtons(true);
  442. $parent.removeClass('has-success').addClass('has-error');
  443. validatorName ? $errors.filter('[data-bv-validator="' + validatorName + '"]').show() : $errors.show();
  444. if ($icon) {
  445. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.validating).addClass(this.options.feedbackIcons.invalid).show();
  446. }
  447. break;
  448. case this.STATUS_VALID:
  449. validatorName ? $errors.filter('[data-bv-validator="' + validatorName + '"]').hide() : $errors.hide();
  450. // If the field is valid
  451. if ($errors.filter(function() {
  452. var display = $(this).css('display'), v = $(this).attr('data-bv-validator');
  453. return ('block' == display) || (that.results[field][v] != that.STATUS_VALID);
  454. }).length == 0
  455. ) {
  456. this._disableSubmitButtons(false);
  457. $parent.removeClass('has-error').addClass('has-success');
  458. if ($icon) {
  459. $icon.removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).addClass(this.options.feedbackIcons.valid).show();
  460. }
  461. }
  462. break;
  463. case this.STATUS_NOT_VALIDATED:
  464. default:
  465. this._disableSubmitButtons(false);
  466. $parent.removeClass('has-success').removeClass('has-error');
  467. validatorName ? $errors.filter('.help-block[data-bv-validator="' + validatorName + '"]').hide() : $errors.hide();
  468. if ($icon) {
  469. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).hide();
  470. }
  471. break;
  472. }
  473. return this;
  474. },
  475. // Useful APIs which aren't used internally
  476. /**
  477. * Reset the form
  478. *
  479. * @param {Boolean} resetFormData Reset current form data
  480. * @return {BootstrapValidator}
  481. */
  482. resetForm: function(resetFormData) {
  483. var field, $field, type;
  484. for (field in this.options.fields) {
  485. this.dfds[field] = {};
  486. this.results[field] = {};
  487. $field = this.getFieldElements(field);
  488. // Mark field as not validated yet
  489. this.updateStatus($field, this.STATUS_NOT_VALIDATED, null);
  490. if (resetFormData) {
  491. type = $field.attr('type');
  492. ('radio' == type || 'checkbox' == type) ? $field.removeAttr('checked').removeAttr('selected') : $field.val('');
  493. }
  494. }
  495. this.invalidField = null;
  496. this.$submitButton = null;
  497. // Enable submit buttons
  498. this._disableSubmitButtons(false);
  499. return this;
  500. },
  501. /**
  502. * Enable/Disable all validators to given field
  503. *
  504. * @param {String} field The field name
  505. * @param {Boolean} enabled Enable/Disable field validators
  506. * @return {BootstrapValidator}
  507. */
  508. enableFieldValidators: function(field, enabled) {
  509. this.options.fields[field]['enabled'] = enabled;
  510. this.updateStatus(field, this.STATUS_NOT_VALIDATED, null);
  511. return this;
  512. }
  513. };
  514. // Plugin definition
  515. $.fn.bootstrapValidator = function(options) {
  516. return this.each(function() {
  517. var $this = $(this), data = $this.data('bootstrapValidator');
  518. if (!data) {
  519. $this.data('bootstrapValidator', (data = new BootstrapValidator(this, options)));
  520. }
  521. if ('string' == typeof options) {
  522. data[options]();
  523. }
  524. });
  525. };
  526. // Available validators
  527. $.fn.bootstrapValidator.validators = {};
  528. $.fn.bootstrapValidator.Constructor = BootstrapValidator;
  529. }(window.jQuery));