bootstrapValidator.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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) 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. if ('disabled' == this.options.live) {
  15. // Don't disable the submit buttons if the live validating is disabled
  16. this.options.submitButtons = null;
  17. }
  18. this.invalidFields = {};
  19. this.xhrRequests = {};
  20. this.numPendingRequests = null;
  21. this.formSubmited = false;
  22. this.submitHandlerCalled = false;
  23. this._init();
  24. };
  25. // The default options
  26. BootstrapValidator.DEFAULT_OPTIONS = {
  27. // The form CSS class
  28. elementClass: 'bootstrap-validator-form',
  29. // Default invalid message
  30. message: 'This value is not valid',
  31. // The submit buttons selector
  32. // These buttons will be disabled when the form input are invalid
  33. submitButtons: 'button[type="submit"]',
  34. // The custom submit handler
  35. // It will prevent the form from the default submitting
  36. //
  37. // submitHandler: function(validator, form) {
  38. // - validator is the BootstrapValidator instance
  39. // - form is the jQuery object present the current form
  40. // }
  41. submitHandler: null,
  42. // Live validating. Can be one of 3 values:
  43. // - enabled: The plugin validates fields as soon as they are changed
  44. // - disabled: Disable the live validating. The error messages are only shown after the form is submitted
  45. // - submitted: The live validating is enabled after the form is submitted
  46. live: 'enabled',
  47. // Map the field name with validator rules
  48. fields: null
  49. };
  50. BootstrapValidator.prototype = {
  51. constructor: BootstrapValidator,
  52. /**
  53. * Init form
  54. */
  55. _init: function() {
  56. if (this.options.fields == null) {
  57. return;
  58. }
  59. var that = this;
  60. this.$form
  61. // Disable client side validation in HTML 5
  62. .attr('novalidate', 'novalidate')
  63. .addClass(this.options.elementClass)
  64. .on('submit', function(e) {
  65. that.formSubmited = true;
  66. if (that.options.fields) {
  67. for (var field in that.options.fields) {
  68. if (that.numPendingRequests > 0 || that.numPendingRequests == null) {
  69. // Check if the field is valid
  70. var $field = that.getFieldElement(field);
  71. if ($field.data('bootstrapValidator.isValid') !== true) {
  72. that.validateField(field);
  73. }
  74. }
  75. }
  76. if (!that.isValid()) {
  77. that.$form.find(that.options.submitButtons).attr('disabled', 'disabled');
  78. if ('submitted' == that.options.live) {
  79. that.options.live = 'enabled';
  80. that._setLiveValidating();
  81. }
  82. e.preventDefault();
  83. } else {
  84. if (!that.submitHandlerCalled && that.options.submitHandler && 'function' == typeof that.options.submitHandler) {
  85. // Avoid calling submitHandler recursively
  86. // in the case user call form.submit() right inside the submitHandler()
  87. that.submitHandlerCalled = true;
  88. that.options.submitHandler.call(that, that, that.$form);
  89. return false;
  90. }
  91. }
  92. }
  93. });
  94. for (var field in this.options.fields) {
  95. this._initField(field);
  96. }
  97. this._setLiveValidating();
  98. },
  99. /**
  100. * Enable live validating
  101. */
  102. _setLiveValidating: function() {
  103. if ('enabled' == this.options.live) {
  104. var that = this;
  105. // Since this should be called once, I have to disable the live validating mode
  106. this.options.live = 'disabled';
  107. for (var field in this.options.fields) {
  108. (function(field) {
  109. var $field = that.getFieldElement(field);
  110. if ($field) {
  111. var type = $field.attr('type'),
  112. event = ('checkbox' == type || 'radio' == type || 'SELECT' == $field.get(0).tagName) ? 'change' : 'keyup';
  113. $field.on(event, function() {
  114. that.formSubmited = false;
  115. that.validateField(field);
  116. });
  117. }
  118. })(field);
  119. }
  120. }
  121. },
  122. /**
  123. * Init field
  124. *
  125. * @param {String} field The field name
  126. */
  127. _initField: function(field) {
  128. if (this.options.fields[field] == null || this.options.fields[field].validators == null) {
  129. return;
  130. }
  131. var $field = this.getFieldElement(field);
  132. if (null == $field) {
  133. return;
  134. }
  135. // Create a help block element for showing the error
  136. var that = this,
  137. $parent = $field.parents('.form-group'),
  138. helpBlock = $parent.find('.help-block');
  139. if (helpBlock.length == 0) {
  140. var $small = $('<small/>').addClass('help-block').css('display', 'none').appendTo($parent);
  141. $field.data('bootstrapValidator.error', $small);
  142. // Calculate the number of columns of the label/field element
  143. // Then set offset to the help block element
  144. var label, cssClasses, offset, size;
  145. if (label = $parent.find('label').get(0)) {
  146. cssClasses = $(label).attr('class').split(' ');
  147. for (var i = 0; i < cssClasses.length; i++) {
  148. if (/^col-(xs|sm|md|lg)-\d+$/.test(cssClasses[i])) {
  149. offset = cssClasses[i].substr(7);
  150. size = cssClasses[i].substr(4, 2);
  151. break;
  152. }
  153. }
  154. } else {
  155. cssClasses = $parent.children().eq(0).attr('class').split(' ');
  156. for (var i = 0; i < cssClasses.length; i++) {
  157. if (/^col-(xs|sm|md|lg)-offset-\d+$/.test(cssClasses[i])) {
  158. offset = cssClasses[i].substr(14);
  159. size = cssClasses[i].substr(4, 2);
  160. break;
  161. }
  162. }
  163. }
  164. if (size && offset) {
  165. $small.addClass(['col-', size, '-offset-', offset].join(''))
  166. .addClass(['col-', size, '-', 12 - offset].join(''));
  167. }
  168. } else {
  169. $field.data('bootstrapValidator.error', helpBlock.eq(0));
  170. }
  171. },
  172. /**
  173. * Get field element
  174. *
  175. * @param {String} field The field name
  176. * @returns {jQuery}
  177. */
  178. getFieldElement: function(field) {
  179. var fields = this.$form.find('[name="' + field + '"]');
  180. return (fields.length == 0) ? null : $(fields[0]);
  181. },
  182. /**
  183. * Validate given field
  184. *
  185. * @param {String} field The field name
  186. */
  187. validateField: function(field) {
  188. var $field = this.getFieldElement(field);
  189. if (null == $field) {
  190. // Return if cannot find the field with given name
  191. return;
  192. }
  193. var that = this,
  194. validators = that.options.fields[field].validators;
  195. for (var validatorName in validators) {
  196. if (!$.fn.bootstrapValidator.validators[validatorName]) {
  197. continue;
  198. }
  199. var isValid = $.fn.bootstrapValidator.validators[validatorName].validate(that, $field, validators[validatorName]);
  200. if (isValid === false) {
  201. that.showError($field, validatorName);
  202. break;
  203. } else if (isValid === true) {
  204. that.removeError($field);
  205. }
  206. }
  207. },
  208. /**
  209. * Show field error
  210. *
  211. * @param {jQuery} $field The field element
  212. * @param {String} validatorName
  213. */
  214. showError: function($field, validatorName) {
  215. var field = $field.attr('name'),
  216. validator = this.options.fields[field].validators[validatorName],
  217. message = validator.message || this.options.message,
  218. $parent = $field.parents('.form-group');
  219. this.invalidFields[field] = true;
  220. // Add has-error class to parent element
  221. $parent.removeClass('has-success').addClass('has-error');
  222. $field.data('bootstrapValidator.error').html(message).show();
  223. this.$form.find(this.options.submitButtons).attr('disabled', 'disabled');
  224. },
  225. /**
  226. * Remove error from given field
  227. *
  228. * @param {jQuery} $field The field element
  229. */
  230. removeError: function($field) {
  231. delete this.invalidFields[$field.attr('name')];
  232. $field.parents('.form-group').removeClass('has-error').addClass('has-success');
  233. $field.data('bootstrapValidator.error').hide();
  234. this.$form.find(this.options.submitButtons).removeAttr('disabled');
  235. },
  236. /**
  237. * Start remote checking
  238. *
  239. * @param {jQuery} $field The field element
  240. * @param {String} validatorName
  241. * @param {XMLHttpRequest} xhr
  242. */
  243. startRequest: function($field, validatorName, xhr) {
  244. var field = $field.attr('name');
  245. $field.data('bootstrapValidator.isValid', false);
  246. this.$form.find(this.options.submitButtons).attr('disabled', 'disabled');
  247. if(this.numPendingRequests == null){
  248. this.numPendingRequests = 0;
  249. }
  250. this.numPendingRequests++;
  251. // Abort the previous request
  252. if (!this.xhrRequests[field]) {
  253. this.xhrRequests[field] = {};
  254. }
  255. if (this.xhrRequests[field][validatorName]) {
  256. this.numPendingRequests--;
  257. this.xhrRequests[field][validatorName].abort();
  258. }
  259. this.xhrRequests[field][validatorName] = xhr;
  260. },
  261. /**
  262. * Complete remote checking
  263. *
  264. * @param {jQuery} $field The field element
  265. * @param {String} validatorName
  266. * @param {Boolean} isValid
  267. */
  268. completeRequest: function($field, validatorName, isValid) {
  269. if (isValid === false) {
  270. this.showError($field, validatorName);
  271. } else if (isValid === true) {
  272. this.removeError($field);
  273. $field.data('bootstrapValidator.isValid', true);
  274. }
  275. var field = $field.attr('name');
  276. delete this.xhrRequests[field][validatorName];
  277. this.numPendingRequests--;
  278. if (this.numPendingRequests <= 0) {
  279. this.numPendingRequests = 0;
  280. if (this.formSubmited) {
  281. if (this.options.submitHandler && 'function' == typeof this.options.submitHandler) {
  282. this.options.submitHandler.call(this, this, this.$form);
  283. } else {
  284. this.$form.submit();
  285. }
  286. }
  287. }
  288. },
  289. /**
  290. * Check the form validity
  291. *
  292. * @returns {Boolean}
  293. */
  294. isValid: function() {
  295. if (this.numPendingRequests > 0) {
  296. return false;
  297. }
  298. for (var field in this.invalidFields) {
  299. if (this.invalidFields[field]) {
  300. return false;
  301. }
  302. }
  303. return true;
  304. }
  305. };
  306. // Plugin definition
  307. $.fn.bootstrapValidator = function(options) {
  308. return this.each(function() {
  309. var $this = $(this), data = $this.data('bootstrapValidator');
  310. if (!data) {
  311. $this.data('bootstrapValidator', (data = new BootstrapValidator(this, options)));
  312. }
  313. });
  314. };
  315. // Available validators
  316. $.fn.bootstrapValidator.validators = {};
  317. $.fn.bootstrapValidator.Constructor = BootstrapValidator;
  318. }(window.jQuery));