bootstrapValidator.js 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292
  1. /**
  2. * BootstrapValidator (http://bootstrapvalidator.com)
  3. *
  4. * The best jQuery plugin to validate form fields. Designed to 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.$invalidFields = $([]); // Array of invalid fields
  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. // Get IE version
  25. // https://gist.github.com/padolsey/527683/#comment-7595
  26. var ieVersion = (function() {
  27. var v = 3, div = document.createElement('div'), a = div.all || [];
  28. while (div.innerHTML = '<!--[if gt IE '+(++v)+']><br><![endif]-->', a[0]);
  29. return v > 4 ? v : !v;
  30. }());
  31. var el = document.createElement('div');
  32. this._changeEvent = (ieVersion === 9 || !('oninput' in el)) ? 'keyup' : 'input';
  33. // The flag to indicate that the form is ready to submit when a remote/callback validator returns
  34. this._submitIfValid = null;
  35. // Field elements
  36. this._cacheFields = {};
  37. this._init();
  38. };
  39. // The default options
  40. BootstrapValidator.DEFAULT_OPTIONS = {
  41. // The form CSS class
  42. elementClass: 'bv-form',
  43. // Default invalid message
  44. message: 'This value is not valid',
  45. // The error messages container
  46. // It can be:
  47. // * 'tooltip' if you want to use Bootstrap tooltip to show error messages
  48. // * 'popover' if you want to use Bootstrap popover to show error messages
  49. // * a CSS selector indicating the container
  50. //
  51. // In the first two cases, since the tooltip/popover should be small enough, the plugin only shows only one error message
  52. // You also can define the message container for particular field
  53. container: null,
  54. // The field will not be live validated if its length is less than this number of characters
  55. threshold: null,
  56. // Indicate fields which won't be validated
  57. // By default, the plugin will not validate the following kind of fields:
  58. // - disabled
  59. // - hidden
  60. // - invisible
  61. //
  62. // The setting consists of jQuery filters. Accept 3 formats:
  63. // - A string. Use a comma to separate filter
  64. // - An array. Each element is a filter
  65. // - An array. Each element can be a callback function
  66. // function($field, validator) {
  67. // $field is jQuery object representing the field element
  68. // validator is the BootstrapValidator instance
  69. // return true or false;
  70. // }
  71. //
  72. // The 3 following settings are equivalent:
  73. //
  74. // 1) ':disabled, :hidden, :not(:visible)'
  75. // 2) [':disabled', ':hidden', ':not(:visible)']
  76. // 3) [':disabled', ':hidden', function($field) {
  77. // return !$field.is(':visible');
  78. // }]
  79. excluded: [':disabled', ':hidden', ':not(:visible)'],
  80. // Shows ok/error/loading icons based on the field validity.
  81. // This feature requires Bootstrap v3.1.0 or later (http://getbootstrap.com/css/#forms-control-validation).
  82. // Since Bootstrap doesn't provide any methods to know its version, this option cannot be on/off automatically.
  83. // In other word, to use this feature you have to upgrade your Bootstrap to v3.1.0 or later.
  84. //
  85. // Examples:
  86. // - Use Glyphicons icons:
  87. // feedbackIcons: {
  88. // valid: 'glyphicon glyphicon-ok',
  89. // invalid: 'glyphicon glyphicon-remove',
  90. // validating: 'glyphicon glyphicon-refresh'
  91. // }
  92. // - Use FontAwesome icons:
  93. // feedbackIcons: {
  94. // valid: 'fa fa-check',
  95. // invalid: 'fa fa-times',
  96. // validating: 'fa fa-refresh'
  97. // }
  98. feedbackIcons: {
  99. valid: null,
  100. invalid: null,
  101. validating: null
  102. },
  103. // The submit buttons selector
  104. // These buttons will be disabled to prevent the valid form from multiple submissions
  105. submitButtons: '[type="submit"]',
  106. // The custom submit handler
  107. // It will prevent the form from the default submission
  108. //
  109. // submitHandler: function(validator, form) {
  110. // - validator is the BootstrapValidator instance
  111. // - form is the jQuery object present the current form
  112. // }
  113. submitHandler: null,
  114. // Live validating option
  115. // Can be one of 3 values:
  116. // - enabled: The plugin validates fields as soon as they are changed
  117. // - disabled: Disable the live validating. The error messages are only shown after the form is submitted
  118. // - submitted: The live validating is enabled after the form is submitted
  119. live: 'enabled',
  120. // Map the field name with validator rules
  121. fields: null
  122. };
  123. BootstrapValidator.prototype = {
  124. constructor: BootstrapValidator,
  125. /**
  126. * Init form
  127. */
  128. _init: function() {
  129. var that = this,
  130. options = {
  131. excluded: this.$form.attr('data-bv-excluded'),
  132. trigger: this.$form.attr('data-bv-trigger'),
  133. message: this.$form.attr('data-bv-message'),
  134. container: this.$form.attr('data-bv-container'),
  135. submitButtons: this.$form.attr('data-bv-submitbuttons'),
  136. threshold: this.$form.attr('data-bv-threshold'),
  137. live: this.$form.attr('data-bv-live'),
  138. fields: {},
  139. feedbackIcons: {
  140. valid: this.$form.attr('data-bv-feedbackicons-valid'),
  141. invalid: this.$form.attr('data-bv-feedbackicons-invalid'),
  142. validating: this.$form.attr('data-bv-feedbackicons-validating')
  143. }
  144. },
  145. validator,
  146. v, // Validator name
  147. enabled,
  148. optionName,
  149. optionValue,
  150. html5AttrName,
  151. html5Attrs;
  152. this.$form
  153. // Disable client side validation in HTML 5
  154. .attr('novalidate', 'novalidate')
  155. .addClass(this.options.elementClass)
  156. // Disable the default submission first
  157. .on('submit.bv', function(e) {
  158. e.preventDefault();
  159. that.validate();
  160. })
  161. .on('click.bv', this.options.submitButtons, function() {
  162. that.$submitButton = $(this);
  163. // The user just click the submit button
  164. that._submitIfValid = true;
  165. })
  166. // Find all fields which have either "name" or "data-bv-field" attribute
  167. .find('[name], [data-bv-field]')
  168. .each(function() {
  169. var $field = $(this);
  170. if (that._isExcluded($field)) {
  171. return;
  172. }
  173. var field = $field.attr('name') || $field.attr('data-bv-field'),
  174. validators = {};
  175. for (v in $.fn.bootstrapValidator.validators) {
  176. validator = $.fn.bootstrapValidator.validators[v];
  177. enabled = $field.attr('data-bv-' + v.toLowerCase()) + '';
  178. html5Attrs = ('function' == typeof validator.enableByHtml5) ? validator.enableByHtml5($(this)) : null;
  179. if ((html5Attrs && enabled != 'false')
  180. || (html5Attrs !== true && ('' == enabled || 'true' == enabled)))
  181. {
  182. // Try to parse the options via attributes
  183. validator.html5Attributes = validator.html5Attributes || { message: 'message' };
  184. validators[v] = $.extend({}, html5Attrs == true ? {} : html5Attrs, validators[v]);
  185. for (html5AttrName in validator.html5Attributes) {
  186. optionName = validator.html5Attributes[html5AttrName];
  187. optionValue = $field.attr('data-bv-' + v.toLowerCase() + '-' + html5AttrName);
  188. if (optionValue) {
  189. if ('true' == optionValue) {
  190. optionValue = true;
  191. } else if ('false' == optionValue) {
  192. optionValue = false;
  193. }
  194. validators[v][optionName] = optionValue;
  195. }
  196. }
  197. }
  198. }
  199. var opts = {
  200. feedbackIcons: $field.attr('data-bv-feedbackicons'),
  201. trigger: $field.attr('data-bv-trigger'),
  202. message: $field.attr('data-bv-message'),
  203. container: $field.attr('data-bv-container'),
  204. selector: $field.attr('data-bv-selector'),
  205. threshold: $field.attr('data-bv-threshold')
  206. },
  207. emptyOptions = $.isEmptyObject(opts), // Check if the field options are set using HTML attributes
  208. emptyValidators = $.isEmptyObject(validators); // Check if the field validators are set using HTML attributes
  209. if (!emptyValidators || (!emptyOptions && that.options.fields[field])) {
  210. opts.validators = validators;
  211. $field.attr('data-bv-field', field);
  212. options.fields[field] = $.extend({}, opts, options.fields[field]);
  213. }
  214. });
  215. this.options = $.extend(true, this.options, options);
  216. for (var field in this.options.fields) {
  217. this._initField(field);
  218. }
  219. },
  220. /**
  221. * Init field
  222. *
  223. * @param {String} field The field name
  224. */
  225. _initField: function(field) {
  226. if (this.options.fields[field] == null || this.options.fields[field].validators == null) {
  227. return;
  228. }
  229. var fields = this.getFieldElements(field);
  230. // We don't need to validate non-existing fields
  231. if (fields == []) {
  232. delete this.options.fields[field];
  233. return;
  234. }
  235. for (var validatorName in this.options.fields[field].validators) {
  236. if (!$.fn.bootstrapValidator.validators[validatorName]) {
  237. delete this.options.fields[field].validators[validatorName];
  238. }
  239. }
  240. if (this.options.fields[field]['enabled'] == null) {
  241. this.options.fields[field]['enabled'] = true;
  242. }
  243. for (var i = 0; i < fields.length; i++) {
  244. this._initFieldElement($(fields[i]));
  245. }
  246. },
  247. /**
  248. * Init field element
  249. *
  250. * @param {jQuery} $field The field element
  251. */
  252. _initFieldElement: function($field) {
  253. var that = this,
  254. field = $field.attr('name') || $field.attr('data-bv-field'),
  255. fields = this.getFieldElements(field),
  256. index = fields.index($field),
  257. type = $field.attr('type'),
  258. total = fields.length,
  259. updateAll = (total == 1) || ('radio' == type) || ('checkbox' == type),
  260. $parent = $field.parents('.form-group'),
  261. // Allow user to indicate where the error messages are shown
  262. container = this.options.fields[field].container || this.options.container,
  263. $message = (container && container != 'tooltip' && container != 'popover') ? $(container) : this._getMessageContainer($field);
  264. if (container && container != 'tooltip' && container != 'popover') {
  265. $message.addClass('has-error');
  266. }
  267. // Remove all error messages and feedback icons
  268. $message.find('.help-block[data-bv-validator][data-bv-for="' + field + '"]').remove();
  269. $parent.find('i[data-bv-icon-for="' + field + '"]').remove();
  270. // Set the attribute to indicate the fields which are defined by selector
  271. if (!$field.attr('data-bv-field')) {
  272. $field.attr('data-bv-field', field);
  273. }
  274. // Whenever the user change the field value, mark it as not validated yet
  275. var event = ('radio' == type || 'checkbox' == type || 'file' == type || 'SELECT' == $field.get(0).tagName) ? 'change' : this._changeEvent;
  276. $field.off(event + '.update.bv').on(event + '.update.bv', function() {
  277. // Reset the flag
  278. that._submitIfValid = false;
  279. that.updateElementStatus($(this), that.STATUS_NOT_VALIDATED);
  280. });
  281. // Create help block elements for showing the error messages
  282. $field.data('bv.messages', $message);
  283. for (var validatorName in this.options.fields[field].validators) {
  284. $field.data('bv.result.' + validatorName, this.STATUS_NOT_VALIDATED);
  285. if (!updateAll || index == total - 1) {
  286. $('<small/>')
  287. .css('display', 'none')
  288. .addClass('help-block')
  289. .attr('data-bv-validator', validatorName)
  290. .attr('data-bv-for', field)
  291. .html(this.options.fields[field].validators[validatorName].message || this.options.fields[field].message || this.options.message)
  292. .appendTo($message);
  293. }
  294. }
  295. // Prepare the feedback icons
  296. // Available from Bootstrap 3.1 (http://getbootstrap.com/css/#forms-control-validation)
  297. if (this.options.fields[field].feedbackIcons !== false && this.options.fields[field].feedbackIcons !== 'false'
  298. && this.options.feedbackIcons
  299. && this.options.feedbackIcons.validating && this.options.feedbackIcons.invalid && this.options.feedbackIcons.valid
  300. && (!updateAll || index == total - 1))
  301. {
  302. $parent.removeClass('has-success').removeClass('has-error').addClass('has-feedback');
  303. var $icon = $('<i/>').css('display', 'none').addClass('form-control-feedback').attr('data-bv-icon-for', field).insertAfter($field);
  304. // The feedback icon does not render correctly if there is no label
  305. // https://github.com/twbs/bootstrap/issues/12873
  306. if ($parent.find('label').length == 0) {
  307. $icon.css('top', 0);
  308. }
  309. // Fix feedback icons in input-group
  310. if ($parent.find('.input-group-addon').length != 0) {
  311. $icon.css({
  312. 'top': 0,
  313. 'z-index': 100
  314. });
  315. }
  316. }
  317. // Set live mode
  318. var trigger = this.options.fields[field].trigger || this.options.trigger || event,
  319. events = $.map(trigger.split(' '), function(item) {
  320. return item + '.live.bv';
  321. }).join(' ');
  322. switch (this.options.live) {
  323. case 'submitted':
  324. break;
  325. case 'disabled':
  326. $field.off(events);
  327. break;
  328. case 'enabled':
  329. default:
  330. $field.off(events).on(events, function() {
  331. that.validateFieldElement($(this));
  332. });
  333. break;
  334. }
  335. },
  336. /**
  337. * Get the element to place the error messages
  338. *
  339. * @param {jQuery} $field The field element
  340. * @returns {jQuery}
  341. */
  342. _getMessageContainer: function($field) {
  343. var $parent = $field.parent();
  344. if ($parent.hasClass('form-group')) {
  345. return $parent;
  346. }
  347. var cssClasses = $parent.attr('class');
  348. if (!cssClasses) {
  349. return this._getMessageContainer($parent);
  350. }
  351. cssClasses = cssClasses.split(' ');
  352. var n = cssClasses.length;
  353. for (var i = 0; i < n; i++) {
  354. if (/^col-(xs|sm|md|lg)-\d+$/.test(cssClasses[i]) || /^col-(xs|sm|md|lg)-offset-\d+$/.test(cssClasses[i])) {
  355. return $parent;
  356. }
  357. }
  358. return this._getMessageContainer($parent);
  359. },
  360. /**
  361. * Called when all validations are completed
  362. */
  363. _submit: function() {
  364. var isValid = this.isValid(),
  365. eventType = isValid ? 'success.form.bv' : 'error.form.bv',
  366. e = $.Event(eventType);
  367. this.$form.trigger(e);
  368. // Call default handler
  369. // Check if whether the submit button is clicked
  370. if (this.$submitButton) {
  371. isValid ? this._onSuccess(e) : this._onError(e);
  372. }
  373. },
  374. /**
  375. * Check if the field is excluded.
  376. * Returning true means that the field will not be validated
  377. *
  378. * @param {jQuery} $field The field element
  379. * @returns {Boolean}
  380. */
  381. _isExcluded: function($field) {
  382. if (this.options.excluded) {
  383. // Convert to array first
  384. if ('string' == typeof this.options.excluded) {
  385. this.options.excluded = $.map(this.options.excluded.split(','), function(item) {
  386. // Trim the spaces
  387. return $.trim(item);
  388. });
  389. }
  390. var length = this.options.excluded.length;
  391. for (var i = 0; i < length; i++) {
  392. if (('string' == typeof this.options.excluded[i] && $field.is(this.options.excluded[i]))
  393. || ('function' == typeof this.options.excluded[i] && this.options.excluded[i].call(this, $field, this) == true))
  394. {
  395. return true;
  396. }
  397. }
  398. }
  399. return false;
  400. },
  401. // --- Events ---
  402. /**
  403. * The default handler of error.form.bv event.
  404. * It will be called when there is a invalid field
  405. *
  406. * @param {jQuery.Event} e The jQuery event object
  407. */
  408. _onError: function(e) {
  409. if (e.isDefaultPrevented()) {
  410. return;
  411. }
  412. if ('submitted' == this.options.live) {
  413. // Enable live mode
  414. this.options.live = 'enabled';
  415. var that = this;
  416. for (var field in this.options.fields) {
  417. (function(f) {
  418. var fields = that.getFieldElements(f);
  419. if (fields.length) {
  420. var type = $(fields[0]).attr('type'),
  421. event = ('radio' == type || 'checkbox' == type || 'file' == type || 'SELECT' == $(fields[0]).get(0).tagName) ? 'change' : that._changeEvent,
  422. trigger = that.options.fields[field].trigger || that.options.trigger || event,
  423. events = $.map(trigger.split(' '), function(item) {
  424. return item + '.live.bv';
  425. }).join(' ');
  426. for (var i = 0; i < fields.length; i++) {
  427. $(fields[i]).off(events).on(events, function() {
  428. that.validateFieldElement($(this));
  429. });
  430. }
  431. }
  432. })(field);
  433. }
  434. }
  435. // Focus to the first invalid field
  436. this.$invalidFields.eq(0).focus();
  437. },
  438. /**
  439. * The default handler of success.form.bv event.
  440. * It will be called when all the fields are valid
  441. *
  442. * @param {jQuery.Event} e The jQuery event object
  443. */
  444. _onSuccess: function(e) {
  445. if (e.isDefaultPrevented()) {
  446. return;
  447. }
  448. // Call the custom submission if enabled
  449. if (this.options.submitHandler && 'function' == typeof this.options.submitHandler) {
  450. // If you want to submit the form inside your submit handler, please call defaultSubmit() method
  451. this.options.submitHandler.call(this, this, this.$form, this.$submitButton);
  452. } else {
  453. this.disableSubmitButtons(true).defaultSubmit();
  454. }
  455. },
  456. /**
  457. * Called after validating a field element
  458. *
  459. * @param {jQuery} $field The field element
  460. */
  461. _onValidateFieldCompleted: function($field) {
  462. var field = $field.attr('data-bv-field'),
  463. validators = this.options.fields[field].validators,
  464. counter = {},
  465. numValidators = 0;
  466. counter[this.STATUS_NOT_VALIDATED] = 0;
  467. counter[this.STATUS_VALIDATING] = 0;
  468. counter[this.STATUS_INVALID] = 0;
  469. counter[this.STATUS_VALID] = 0;
  470. for (var validatorName in validators) {
  471. numValidators++;
  472. var result = $field.data('bv.result.' + validatorName);
  473. if (result) {
  474. counter[result]++;
  475. }
  476. }
  477. var index = this.$invalidFields.index($field);
  478. if (counter[this.STATUS_VALID] == numValidators) {
  479. // Remove from the list of invalid fields
  480. if (index != -1) {
  481. this.$invalidFields.splice(index, 1);
  482. }
  483. this.$form.trigger($.Event('success.field.bv'), [field, $field]);
  484. }
  485. // If all validators are completed and there is at least one validator which doesn't pass
  486. else if (counter[this.STATUS_NOT_VALIDATED] == 0 && counter[this.STATUS_VALIDATING] == 0 && counter[this.STATUS_INVALID] > 0) {
  487. // Add to the list of invalid fields
  488. if (index == -1) {
  489. this.$invalidFields = this.$invalidFields.add($field);
  490. }
  491. this.$form.trigger($.Event('error.field.bv'), [field, $field]);
  492. }
  493. },
  494. // --- Public methods ---
  495. /**
  496. * Retrieve the field elements by given name
  497. *
  498. * @param {String} field The field name
  499. * @returns {null|jQuery[]}
  500. */
  501. getFieldElements: function(field) {
  502. if (!this._cacheFields[field]) {
  503. this._cacheFields[field] = this.options.fields[field].selector
  504. ? $(this.options.fields[field].selector)
  505. : this.$form.find('[name="' + field + '"]');
  506. }
  507. return this._cacheFields[field];
  508. },
  509. /**
  510. * Disable/enable submit buttons
  511. *
  512. * @param {Boolean} disabled Can be true or false
  513. * @returns {BootstrapValidator}
  514. */
  515. disableSubmitButtons: function(disabled) {
  516. if (!disabled) {
  517. this.$form.find(this.options.submitButtons).removeAttr('disabled');
  518. } else if (this.options.live != 'disabled') {
  519. // Don't disable if the live validating mode is disabled
  520. this.$form.find(this.options.submitButtons).attr('disabled', 'disabled');
  521. }
  522. return this;
  523. },
  524. /**
  525. * Validate the form
  526. *
  527. * @returns {BootstrapValidator}
  528. */
  529. validate: function() {
  530. if (!this.options.fields) {
  531. return this;
  532. }
  533. this.disableSubmitButtons(true);
  534. for (var field in this.options.fields) {
  535. this.validateField(field);
  536. }
  537. this._submit();
  538. return this;
  539. },
  540. /**
  541. * Validate given field
  542. *
  543. * @param {String} field The field name
  544. * @returns {BootstrapValidator}
  545. */
  546. validateField: function(field) {
  547. var fields = this.getFieldElements(field),
  548. type = fields.attr('type'),
  549. n = (('radio' == type) || ('checkbox' == type)) ? 1 : fields.length;
  550. for (var i = 0; i < n; i++) {
  551. this.validateFieldElement($(fields[i]));
  552. }
  553. return this;
  554. },
  555. /**
  556. * Validate field element
  557. *
  558. * @param {jQuery} $field The field element
  559. * @returns {BootstrapValidator}
  560. */
  561. validateFieldElement: function($field) {
  562. var that = this,
  563. field = $field.attr('data-bv-field'),
  564. fields = this.getFieldElements(field),
  565. type = $field.attr('type'),
  566. updateAll = (fields && fields.length == 1) || ('radio' == type) || ('checkbox' == type),
  567. validators = this.options.fields[field].validators,
  568. validatorName,
  569. validateResult;
  570. if (!this.options.fields[field]['enabled'] || this._isExcluded($field)) {
  571. return this;
  572. }
  573. for (validatorName in validators) {
  574. if ($field.data('bv.dfs.' + validatorName)) {
  575. $field.data('bv.dfs.' + validatorName).reject();
  576. }
  577. // Don't validate field if it is already done
  578. var result = $field.data('bv.result.' + validatorName);
  579. if (result == this.STATUS_VALID || result == this.STATUS_INVALID) {
  580. this._onValidateFieldCompleted($field);
  581. continue;
  582. }
  583. $field.data('bv.result.' + validatorName, this.STATUS_VALIDATING);
  584. validateResult = $.fn.bootstrapValidator.validators[validatorName].validate(this, $field, validators[validatorName]);
  585. // validateResult can be a $.Deferred object ...
  586. if ('object' == typeof validateResult) {
  587. updateAll ? this.updateStatus(field, this.STATUS_VALIDATING, validatorName)
  588. : this.updateElementStatus($field, this.STATUS_VALIDATING, validatorName);
  589. $field.data('bv.dfs.' + validatorName, validateResult);
  590. validateResult.done(function($f, v, isValid, message) {
  591. // v is validator name
  592. $f.removeData('bv.dfs.' + v);
  593. if (message) {
  594. // Update the error message
  595. $field.data('bv.messages').find('.help-block[data-bv-validator="' + v + '"][data-bv-for="' + $f.attr('data-bv-field') + '"]').html(message);
  596. }
  597. updateAll ? that.updateStatus($f.attr('data-bv-field'), isValid ? that.STATUS_VALID : that.STATUS_INVALID, v)
  598. : that.updateElementStatus($f, isValid ? that.STATUS_VALID : that.STATUS_INVALID, v);
  599. if (isValid && that._submitIfValid == true) {
  600. // If a remote validator returns true and the form is ready to submit, then do it
  601. that._submit();
  602. }
  603. });
  604. }
  605. // ... or a boolean value
  606. else if ('boolean' == typeof validateResult) {
  607. updateAll ? this.updateStatus(field, validateResult ? this.STATUS_VALID : this.STATUS_INVALID, validatorName)
  608. : this.updateElementStatus($field, validateResult ? this.STATUS_VALID : this.STATUS_INVALID, validatorName);
  609. }
  610. }
  611. return this;
  612. },
  613. /**
  614. * Update all validating results of elements which have the same field name
  615. *
  616. * @param {String} field The field name
  617. * @param {String} status The status. Can be 'NOT_VALIDATED', 'VALIDATING', 'INVALID' or 'VALID'
  618. * @param {String} [validatorName] The validator name. If null, the method updates validity result for all validators
  619. * @returns {BootstrapValidator}
  620. */
  621. updateStatus: function(field, status, validatorName) {
  622. var fields = this.getFieldElements(field),
  623. type = fields.attr('type'),
  624. n = (('radio' == type) || ('checkbox' == type)) ? 1 : fields.length;
  625. for (var i = 0; i < n; i++) {
  626. this.updateElementStatus($(fields[i]), status, validatorName);
  627. }
  628. return this;
  629. },
  630. /**
  631. * Update validating result of given element
  632. *
  633. * @param {jQuery} $field The field element
  634. * @param {String} status The status. Can be 'NOT_VALIDATED', 'VALIDATING', 'INVALID' or 'VALID'
  635. * @param {String} [validatorName] The validator name. If null, the method updates validity result for all validators
  636. * @returns {BootstrapValidator}
  637. */
  638. updateElementStatus: function($field, status, validatorName) {
  639. var that = this,
  640. field = $field.attr('data-bv-field'),
  641. $parent = $field.parents('.form-group'),
  642. $message = $field.data('bv.messages'),
  643. $allErrors = $message.find('.help-block[data-bv-validator][data-bv-for="' + field + '"]'),
  644. $errors = validatorName ? $allErrors.filter('[data-bv-validator="' + validatorName + '"]') : $allErrors,
  645. $icon = $parent.find('.form-control-feedback[data-bv-icon-for="' + field + '"]'),
  646. container = this.options.fields[field].container || this.options.container,
  647. isValidField = null;
  648. // Update status
  649. if (validatorName) {
  650. $field.data('bv.result.' + validatorName, status);
  651. } else {
  652. for (var v in this.options.fields[field].validators) {
  653. $field.data('bv.result.' + v, status);
  654. }
  655. }
  656. // Show/hide error elements and feedback icons
  657. $errors.attr('data-bv-result', status);
  658. switch (status) {
  659. case this.STATUS_VALIDATING:
  660. isValidField = null;
  661. this.disableSubmitButtons(true);
  662. $parent.removeClass('has-success').removeClass('has-error');
  663. if ($icon) {
  664. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).addClass(this.options.feedbackIcons.validating).show();
  665. }
  666. break;
  667. case this.STATUS_INVALID:
  668. isValidField = false;
  669. this.disableSubmitButtons(true);
  670. $parent.removeClass('has-success').addClass('has-error');
  671. if ($icon) {
  672. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.validating).addClass(this.options.feedbackIcons.invalid).show();
  673. }
  674. break;
  675. case this.STATUS_VALID:
  676. // If the field is valid (passes all validators)
  677. isValidField = $allErrors.filter(function() {
  678. var v = $(this).attr('data-bv-validator');
  679. return $field.data('bv.result.' + v) != that.STATUS_VALID;
  680. }).length == 0;
  681. this.disableSubmitButtons(this.$submitButton ? !this.isValid() : !isValidField);
  682. if ($icon) {
  683. $icon
  684. .removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).removeClass(this.options.feedbackIcons.valid)
  685. .addClass(isValidField ? this.options.feedbackIcons.valid : this.options.feedbackIcons.invalid)
  686. .show();
  687. }
  688. $parent.removeClass('has-error has-success').addClass(this.isValidContainer($parent) ? 'has-success' : 'has-error');
  689. break;
  690. case this.STATUS_NOT_VALIDATED:
  691. default:
  692. isValidField = null;
  693. this.disableSubmitButtons(false);
  694. $parent.removeClass('has-success').removeClass('has-error');
  695. if ($icon) {
  696. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).hide();
  697. }
  698. break;
  699. }
  700. switch (true) {
  701. // Only show the first error message if it is placed inside a tooltip ...
  702. case ($icon && 'tooltip' == container):
  703. (isValidField === false)
  704. ? $icon.css('cursor', 'pointer').tooltip('destroy').tooltip({
  705. html: true,
  706. placement: 'top',
  707. title: $allErrors.filter('[data-bv-result="' + that.STATUS_INVALID + '"]').eq(0).html()
  708. })
  709. : $icon.css('cursor', '').tooltip('destroy');
  710. break;
  711. // ... or popover
  712. case ($icon && 'popover' == container):
  713. (isValidField === false)
  714. ? $icon.css('cursor', 'pointer').popover('destroy').popover({
  715. content: $allErrors.filter('[data-bv-result="' + that.STATUS_INVALID + '"]').eq(0).html(),
  716. html: true,
  717. placement: 'top',
  718. trigger: 'hover click'
  719. })
  720. : $icon.css('cursor', '').popover('destroy');
  721. break;
  722. default:
  723. (status == this.STATUS_INVALID) ? $errors.show() : $errors.hide();
  724. break;
  725. }
  726. // Trigger the "status.field.bv" event
  727. this.$form.trigger($.Event('status.field.bv'), [field, $field, status]);
  728. this._onValidateFieldCompleted($field);
  729. return this;
  730. },
  731. /**
  732. * Check the form validity
  733. *
  734. * @returns {Boolean}
  735. */
  736. isValid: function() {
  737. var fields, field, $field,
  738. type, status, validatorName,
  739. n, i;
  740. for (field in this.options.fields) {
  741. if (this.options.fields[field] == null || !this.options.fields[field]['enabled']) {
  742. continue;
  743. }
  744. fields = this.getFieldElements(field);
  745. type = fields.attr('type');
  746. n = (('radio' == type) || ('checkbox' == type)) ? 1 : fields.length;
  747. for (i = 0; i < n; i++) {
  748. $field = $(fields[i]);
  749. if (this._isExcluded($field)) {
  750. continue;
  751. }
  752. for (validatorName in this.options.fields[field].validators) {
  753. status = $field.data('bv.result.' + validatorName);
  754. if (status != this.STATUS_VALID) {
  755. return false;
  756. }
  757. }
  758. }
  759. }
  760. return true;
  761. },
  762. /**
  763. * Check if all fields inside a given container are valid.
  764. * It's useful when working with a wizard-like such as tab, collapse
  765. *
  766. * @param {jQuery} $container The container element
  767. * @returns {Boolean}
  768. */
  769. isValidContainer: function($container) {
  770. var that = this, map = {};
  771. $container.find('[data-bv-field]').each(function() {
  772. var field = $(this).attr('data-bv-field');
  773. if (!map[field]) {
  774. map[field] = $(this);
  775. }
  776. });
  777. for (var field in map) {
  778. var $f = map[field];
  779. if ($f.data('bv.messages')
  780. .find('.help-block[data-bv-validator][data-bv-for="' + field + '"]')
  781. .filter(function() {
  782. var v = $(this).attr('data-bv-validator');
  783. return ($f.data('bv.result.' + v) && $f.data('bv.result.' + v) != that.STATUS_VALID);
  784. })
  785. .length != 0)
  786. {
  787. // The field is not valid
  788. return false;
  789. }
  790. }
  791. return true;
  792. },
  793. /**
  794. * Submit the form using default submission.
  795. * It also does not perform any validations when submitting the form
  796. *
  797. * It might be used when you want to submit the form right inside the submitHandler()
  798. */
  799. defaultSubmit: function() {
  800. if (this.$submitButton) {
  801. // Create hidden input to send the submit buttons
  802. $('<input/>')
  803. .attr('type', 'hidden')
  804. .attr('data-bv-submit-hidden', '')
  805. .attr('name', this.$submitButton.attr('name'))
  806. .val(this.$submitButton.val())
  807. .appendTo(this.$form);
  808. }
  809. // Submit form
  810. this.$form.off('submit.bv').submit();
  811. },
  812. // Useful APIs which aren't used internally
  813. /**
  814. * Get the list of invalid fields
  815. *
  816. * @returns {jQuery[]}
  817. */
  818. getInvalidFields: function() {
  819. return this.$invalidFields;
  820. },
  821. /**
  822. * Get the error messages
  823. *
  824. * @param {jQuery|String} [field] The field, which can be
  825. * - a string: The field name
  826. * - a jQuery object representing the field element
  827. * If the field is not defined, the method returns all error messages of all fields
  828. * @returns {String[]}
  829. */
  830. getErrors: function(field) {
  831. var that = this,
  832. messages = [],
  833. $fields = $([]);
  834. switch (true) {
  835. case (field && 'object' == typeof field):
  836. $fields = field;
  837. break;
  838. case (field && 'string' == typeof field):
  839. var f = this.getFieldElements(field);
  840. if (f.length > 0) {
  841. var type = f.attr('type');
  842. $fields = ('radio' == type || 'checkbox' == type) ? $(f[0]) : f;
  843. }
  844. break;
  845. default:
  846. $fields = this.$invalidFields;
  847. break;
  848. }
  849. $fields.each(function() {
  850. messages = messages.concat(
  851. $(this)
  852. .data('bv.messages')
  853. .find('.help-block[data-bv-for="' + $(this).attr('data-bv-field') + '"][data-bv-result="' + that.STATUS_INVALID + '"]')
  854. .map(function() {
  855. return $(this).html()
  856. })
  857. .get()
  858. );
  859. });
  860. return messages;
  861. },
  862. /**
  863. * Add new field element
  864. *
  865. * @param {jQuery} $field The field element
  866. * @param {Object} options The field options
  867. * @returns {BootstrapValidator}
  868. */
  869. addFieldElement: function($field, options) {
  870. var field = $field.attr('name') || $field.attr('data-bv-field'),
  871. type = $field.attr('type'),
  872. isNewField = !this._cacheFields[field];
  873. // Update cache
  874. if (!isNewField && this._cacheFields[field].index($field) == -1) {
  875. this._cacheFields[field] = this._cacheFields[field].add($field);
  876. }
  877. if ('checkbox' == type || 'radio' == type || isNewField) {
  878. this._initField(field);
  879. } else {
  880. this._initFieldElement($field);
  881. }
  882. return this;
  883. },
  884. /**
  885. * Remove given field element
  886. *
  887. * @param {jQuery} $field The field element
  888. * @returns {BootstrapValidator}
  889. */
  890. removeFieldElement: function($field) {
  891. var field = $field.attr('name') || $field.attr('data-bv-field'),
  892. type = $field.attr('type'),
  893. index = this._cacheFields[field].index($field);
  894. (index == -1) ? (delete this._cacheFields[field]) : this._cacheFields[field].splice(index, 1);
  895. // Remove from the list of invalid fields
  896. index = this.$invalidFields.index($field);
  897. if (index != -1) {
  898. this.$invalidFields.splice(index, 1);
  899. }
  900. if ('checkbox' == type || 'radio' == type) {
  901. this._initField(field);
  902. }
  903. return this;
  904. },
  905. /**
  906. * Reset the form
  907. *
  908. * @param {Boolean} resetFormData Reset current form data
  909. * @return {BootstrapValidator}
  910. */
  911. resetForm: function(resetFormData) {
  912. var field, fields, total, type, validator;
  913. for (field in this.options.fields) {
  914. fields = this.getFieldElements(field);
  915. total = fields.length;
  916. for (var i = 0; i < total; i++) {
  917. for (validator in this.options.fields[field].validators) {
  918. $(fields[i]).removeData('bv.dfs.' + validator);
  919. }
  920. }
  921. // Mark field as not validated yet
  922. this.updateStatus(field, this.STATUS_NOT_VALIDATED);
  923. if (resetFormData) {
  924. type = fields.attr('type');
  925. ('radio' == type || 'checkbox' == type) ? fields.removeAttr('checked').removeAttr('selected') : fields.val('');
  926. }
  927. }
  928. this.$invalidFields = $([]);
  929. this.$submitButton = null;
  930. // Enable submit buttons
  931. this.disableSubmitButtons(false);
  932. return this;
  933. },
  934. /**
  935. * Enable/Disable all validators to given field
  936. *
  937. * @param {String} field The field name
  938. * @param {Boolean} enabled Enable/Disable field validators
  939. * @returns {BootstrapValidator}
  940. */
  941. enableFieldValidators: function(field, enabled) {
  942. this.options.fields[field]['enabled'] = enabled;
  943. this.updateStatus(field, this.STATUS_NOT_VALIDATED);
  944. return this;
  945. },
  946. /**
  947. * Destroy the plugin
  948. * It will remove all error messages, feedback icons and turn off the events
  949. */
  950. destroy: function() {
  951. var field, fields, $field, validator, $icon, container;
  952. for (field in this.options.fields) {
  953. fields = this.getFieldElements(field);
  954. container = this.options.fields[field].container || this.options.container;
  955. for (var i = 0; i < fields.length; i++) {
  956. $field = $(fields[i]);
  957. $field
  958. // Remove all error messages
  959. .data('bv.messages')
  960. .find('.help-block[data-bv-validator][data-bv-for="' + field + '"]').remove().end()
  961. .end()
  962. .removeData('bv.messages')
  963. // Remove feedback classes
  964. .parents('.form-group')
  965. .removeClass('has-feedback has-error has-success')
  966. .end()
  967. // Turn off events
  968. .off('.bv')
  969. .removeAttr('data-bv-field');
  970. // Remove feedback icons, tooltip/popover container
  971. $icon = $field.parents('.form-group').find('i[data-bv-icon-for="' + field + '"]');
  972. if ($icon) {
  973. switch (container) {
  974. case 'tooltip':
  975. $icon.tooltip('destroy').remove();
  976. break;
  977. case 'popover':
  978. $icon.popover('destroy').remove();
  979. break;
  980. default:
  981. $icon.remove();
  982. break;
  983. }
  984. }
  985. for (validator in this.options.fields[field].validators) {
  986. $field.removeData('bv.result.' + validator).removeData('bv.dfs.' + validator);
  987. }
  988. }
  989. }
  990. // Enable submit buttons
  991. this.disableSubmitButtons(false);
  992. this.$form
  993. .removeClass(this.options.elementClass)
  994. .off('.bv')
  995. .removeData('bootstrapValidator')
  996. // Remove generated hidden elements
  997. .find('[data-bv-submit-hidden]').remove();
  998. },
  999. /**
  1000. * Add a new field validation
  1001. *
  1002. * @param {String} field The field name
  1003. * @param {Object} Map the field name with validator rules
  1004. *
  1005. * @return {BootstrapValidator}
  1006. */
  1007. addField: function(field, properties) {
  1008. this.options.fields[field] = properties;
  1009. this._initField(field);
  1010. return this;
  1011. },
  1012. /**
  1013. * Remove a field validation
  1014. *
  1015. * @param {String} field The field name
  1016. *
  1017. * @return {BootstrapValidator}
  1018. */
  1019. removeField: function(field) {
  1020. delete this.options.fields[field];
  1021. return this;
  1022. }
  1023. };
  1024. // Plugin definition
  1025. $.fn.bootstrapValidator = function(option) {
  1026. var params = arguments;
  1027. return this.each(function() {
  1028. var $this = $(this),
  1029. data = $this.data('bootstrapValidator'),
  1030. options = 'object' == typeof option && option;
  1031. if (!data) {
  1032. data = new BootstrapValidator(this, options);
  1033. $this.data('bootstrapValidator', data);
  1034. }
  1035. // Allow to call plugin method
  1036. if ('string' == typeof option) {
  1037. data[option].apply(data, Array.prototype.slice.call(params, 1));
  1038. }
  1039. });
  1040. };
  1041. // Available validators
  1042. $.fn.bootstrapValidator.validators = {};
  1043. $.fn.bootstrapValidator.Constructor = BootstrapValidator;
  1044. // Helper methods, which can be used in validator class
  1045. $.fn.bootstrapValidator.helpers = {
  1046. /**
  1047. * Validate a date
  1048. *
  1049. * @param {Number} year The full year in 4 digits
  1050. * @param {Number} month The month number
  1051. * @param {Number} day The day number
  1052. * @param {Boolean} [notInFuture] If true, the date must not be in the future
  1053. * @returns {Boolean}
  1054. */
  1055. date: function(year, month, day, notInFuture) {
  1056. if (isNaN(year) || isNaN(month) || isNaN(day)) {
  1057. return false;
  1058. }
  1059. if (year < 1000 || year > 9999 || month == 0 || month > 12) {
  1060. return false;
  1061. }
  1062. var numDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  1063. // Update the number of days in Feb of leap year
  1064. if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
  1065. numDays[1] = 29;
  1066. }
  1067. // Check the day
  1068. if (day < 0 || day > numDays[month - 1]) {
  1069. return false;
  1070. }
  1071. if (notInFuture === true) {
  1072. var currentDate = new Date(),
  1073. currentYear = currentDate.getFullYear(),
  1074. currentMonth = currentDate.getMonth(),
  1075. currentDay = currentDate.getDate();
  1076. return (year < currentYear
  1077. || (year == currentYear && month - 1 < currentMonth)
  1078. || (year == currentYear && month - 1 == currentMonth && day < currentDay));
  1079. }
  1080. return true;
  1081. },
  1082. /**
  1083. * Implement Luhn validation algorithm
  1084. * Credit to https://gist.github.com/ShirtlessKirk/2134376
  1085. *
  1086. * @see http://en.wikipedia.org/wiki/Luhn
  1087. * @param {String} value
  1088. * @returns {Boolean}
  1089. */
  1090. luhn: function(value) {
  1091. var length = value.length,
  1092. mul = 0,
  1093. prodArr = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]],
  1094. sum = 0;
  1095. while (length--) {
  1096. sum += prodArr[mul][parseInt(value.charAt(length), 10)];
  1097. mul ^= 1;
  1098. }
  1099. return (sum % 10 === 0 && sum > 0);
  1100. },
  1101. /**
  1102. * Implement modulus 11, 10 (ISO 7064) algorithm
  1103. *
  1104. * @param {String} value
  1105. * @returns {Boolean}
  1106. */
  1107. mod_11_10: function(value) {
  1108. var check = 5,
  1109. length = value.length;
  1110. for (var i = 0; i < length; i++) {
  1111. check = (((check || 10) * 2) % 11 + parseInt(value.charAt(i), 10)) % 10;
  1112. }
  1113. return (check == 1);
  1114. },
  1115. /**
  1116. * Implements Mod 37, 36 (ISO 7064) algorithm
  1117. * Usages:
  1118. * mod_37_36('A12425GABC1234002M')
  1119. * mod_37_36('002006673085', '0123456789')
  1120. *
  1121. * @param {String} value
  1122. * @param {String} alphabet
  1123. * @returns {Boolean}
  1124. */
  1125. mod_37_36: function(value, alphabet) {
  1126. alphabet = alphabet || '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  1127. var modulus = alphabet.length,
  1128. length = value.length,
  1129. check = Math.floor(modulus / 2);
  1130. for (var i = 0; i < length; i++) {
  1131. check = (((check || modulus) * 2) % (modulus + 1) + alphabet.indexOf(value.charAt(i))) % modulus;
  1132. }
  1133. return (check == 1);
  1134. }
  1135. };
  1136. }(window.jQuery));