bootstrapValidator.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. /**
  2. * BootstrapValidator (https://github.com/nghuuphuoc/bootstrapvalidator)
  3. *
  4. * A jQuery plugin to validate form fields. Use with Bootstrap 3
  5. *
  6. * @author Nguyen Huu Phuoc <phuoc@huuphuoc.me>
  7. * @copyright (c) 2013 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.invalidFields = {};
  15. this.xhrRequests = {};
  16. this.numPendingRequests = null;
  17. this.formSubmited = false;
  18. this._init();
  19. };
  20. // The default options
  21. BootstrapValidator.DEFAULT_OPTIONS = {
  22. // The form CSS class
  23. elementClass: 'bootstrap-validator-form',
  24. // Default invalid message
  25. message: 'This value is not valid',
  26. // The submit buttons selector
  27. // These buttons will be disabled when the form input are invalid
  28. submitButtons: 'button[type="submit"]',
  29. // Map the field name with validator rules
  30. fields: null
  31. };
  32. BootstrapValidator.prototype = {
  33. constructor: BootstrapValidator,
  34. /**
  35. * Init form
  36. */
  37. _init: function() {
  38. if (this.options.fields == null) {
  39. return;
  40. }
  41. var that = this;
  42. this.$form
  43. // Disable client side validation in HTML 5
  44. .attr('novalidate', 'novalidate')
  45. .addClass(this.options.elementClass)
  46. .on('submit', function(e) {
  47. that.formSubmited = true;
  48. if (that.options.fields) {
  49. for (var field in that.options.fields) {
  50. if (that.numPendingRequests > 0 || that.numPendingRequests == null) {
  51. // Check if the field is valid
  52. var $field = that.getFieldElement(field);
  53. if ($field.data('bootstrapValidator.isValid') !== true) {
  54. that.validateField(field);
  55. }
  56. }
  57. }
  58. if (!that.isValid()) {
  59. that.$form.find(that.options.submitButtons).attr('disabled', 'disabled');
  60. e.preventDefault();
  61. }
  62. }
  63. });
  64. for (var field in this.options.fields) {
  65. this._initField(field);
  66. }
  67. },
  68. /**
  69. * Init field
  70. *
  71. * @param {String} field The field name
  72. */
  73. _initField: function(field) {
  74. if (this.options.fields[field] == null || this.options.fields[field].validators == null) {
  75. return;
  76. }
  77. var $field = this.getFieldElement(field);
  78. if (null == $field) {
  79. return;
  80. }
  81. // Create a help block element for showing the error
  82. var that = this,
  83. $parent = $field.parents('.form-group'),
  84. helpBlock = $parent.find('.help-block');
  85. if (helpBlock.length == 0) {
  86. var $small = $('<small/>').addClass('help-block').appendTo($parent);
  87. $field.data('bootstrapValidator.error', $small);
  88. // Calculate the number of columns of the label/field element
  89. // Then set offset to the help block element
  90. var label, cssClasses, offset;
  91. if (label = $parent.find('label').get(0)) {
  92. cssClasses = $(label).attr('class').split(' ');
  93. for (var i = 0; i < cssClasses.length; i++) {
  94. if (cssClasses[i].substr(0, 7) == 'col-lg-') {
  95. offset = cssClasses[i].substr(7);
  96. break;
  97. }
  98. }
  99. } else {
  100. cssClasses = $parent.children().eq(0).attr('class').split(' ');
  101. for (var i = 0; i < cssClasses.length; i++) {
  102. if (cssClasses[i].substr(0, 14) == 'col-lg-offset-') {
  103. offset = cssClasses[i].substr(14);
  104. break;
  105. }
  106. }
  107. }
  108. if (offset) {
  109. $small.addClass('col-lg-offset-' + offset).addClass('col-lg-' + parseInt(12 - offset));
  110. }
  111. } else {
  112. $field.data('bootstrapValidator.error', helpBlock.eq(0));
  113. }
  114. var type = $field.attr('type'),
  115. event = ('checkbox' == type || 'radio' == type || 'SELECT' == $field.get(0).tagName) ? 'change' : 'keyup';
  116. $field.on(event, function() {
  117. that.formSubmited = false;
  118. that.validateField(field);
  119. });
  120. },
  121. /**
  122. * Get field element
  123. *
  124. * @param {String} field The field name
  125. * @returns {jQuery}
  126. */
  127. getFieldElement: function(field) {
  128. var fields = this.$form.find('[name="' + field + '"]');
  129. return (fields.length == 0) ? null : $(fields[0]);
  130. },
  131. /**
  132. * Validate given field
  133. *
  134. * @param {String} field The field name
  135. */
  136. validateField: function(field) {
  137. var $field = this.getFieldElement(field);
  138. if (null == $field) {
  139. // Return if cannot find the field with given name
  140. return;
  141. }
  142. var that = this,
  143. validators = that.options.fields[field].validators;
  144. for (var validatorName in validators) {
  145. if (!$.fn.bootstrapValidator.validators[validatorName]) {
  146. continue;
  147. }
  148. var isValid = $.fn.bootstrapValidator.validators[validatorName].validate(that, $field, validators[validatorName]);
  149. if (isValid === false) {
  150. that.showError($field, validatorName);
  151. break;
  152. } else if (isValid === true) {
  153. that.removeError($field);
  154. }
  155. }
  156. },
  157. /**
  158. * Show field error
  159. *
  160. * @param {jQuery} $field The field element
  161. * @param {String} validatorName
  162. */
  163. showError: function($field, validatorName) {
  164. var field = $field.attr('name'),
  165. validator = this.options.fields[field].validators[validatorName],
  166. message = validator.message || this.options.message,
  167. $parent = $field.parents('.form-group');
  168. this.invalidFields[field] = true;
  169. // Add has-error class to parent element
  170. $parent.removeClass('has-success').addClass('has-error');
  171. $field.data('bootstrapValidator.error').html(message).show();
  172. this.$form.find(this.options.submitButtons).attr('disabled', 'disabled');
  173. },
  174. /**
  175. * Remove error from given field
  176. *
  177. * @param {jQuery} $field The field element
  178. */
  179. removeError: function($field) {
  180. delete this.invalidFields[$field.attr('name')];
  181. $field.parents('.form-group').removeClass('has-error').addClass('has-success');
  182. $field.data('bootstrapValidator.error').hide();
  183. this.$form.find(this.options.submitButtons).removeAttr('disabled');
  184. },
  185. /**
  186. * Start remote checking
  187. *
  188. * @param {jQuery} $field The field element
  189. * @param {String} validatorName
  190. * @param {XMLHttpRequest} xhr
  191. */
  192. startRequest: function($field, validatorName, xhr) {
  193. var field = $field.attr('name');
  194. $field.data('bootstrapValidator.isValid', false);
  195. this.$form.find(this.options.submitButtons).attr('disabled', 'disabled');
  196. if(this.numPendingRequests == null){
  197. this.numPendingRequests = 0;
  198. }
  199. this.numPendingRequests++;
  200. // Abort the previous request
  201. if (!this.xhrRequests[field]) {
  202. this.xhrRequests[field] = {};
  203. }
  204. if (this.xhrRequests[field][validatorName]) {
  205. this.numPendingRequests--;
  206. this.xhrRequests[field][validatorName].abort();
  207. }
  208. this.xhrRequests[field][validatorName] = xhr;
  209. },
  210. /**
  211. * Complete remote checking
  212. *
  213. * @param {jQuery} $field The field element
  214. * @param {String} validatorName
  215. * @param {boolean} isValid
  216. */
  217. completeRequest: function($field, validatorName, isValid) {
  218. if (isValid === false) {
  219. this.showError($field, validatorName);
  220. } else if (isValid === true) {
  221. this.removeError($field);
  222. $field.data('bootstrapValidator.isValid', true);
  223. }
  224. var field = $field.attr('name');
  225. delete this.xhrRequests[field][validatorName];
  226. this.numPendingRequests--;
  227. if (this.numPendingRequests <= 0) {
  228. this.numPendingRequests = 0;
  229. if (this.formSubmited) {
  230. this.$form.submit();
  231. }
  232. }
  233. },
  234. /**
  235. * Check the form validity
  236. *
  237. * @returns {boolean}
  238. */
  239. isValid: function() {
  240. if (this.numPendingRequests > 0) {
  241. return false;
  242. }
  243. for (var field in this.invalidFields) {
  244. if (this.invalidFields[field]) {
  245. return false;
  246. }
  247. }
  248. return true;
  249. }
  250. };
  251. // Plugin definition
  252. $.fn.bootstrapValidator = function(options) {
  253. return this.each(function() {
  254. var $this = $(this), data = $this.data('bootstrapValidator');
  255. if (!data) {
  256. $this.data('bootstrapValidator', (data = new BootstrapValidator(this, options)));
  257. }
  258. });
  259. };
  260. // Available validators
  261. $.fn.bootstrapValidator.validators = {};
  262. $.fn.bootstrapValidator.Constructor = BootstrapValidator;
  263. }(window.jQuery));