bootstrapValidator.js 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  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. // Plugin definition
  1001. $.fn.bootstrapValidator = function(option) {
  1002. var params = arguments;
  1003. return this.each(function() {
  1004. var $this = $(this),
  1005. data = $this.data('bootstrapValidator'),
  1006. options = 'object' == typeof option && option;
  1007. if (!data) {
  1008. data = new BootstrapValidator(this, options);
  1009. $this.data('bootstrapValidator', data);
  1010. }
  1011. // Allow to call plugin method
  1012. if ('string' == typeof option) {
  1013. data[option].apply(data, Array.prototype.slice.call(params, 1));
  1014. }
  1015. });
  1016. };
  1017. // Available validators
  1018. $.fn.bootstrapValidator.validators = {};
  1019. $.fn.bootstrapValidator.Constructor = BootstrapValidator;
  1020. // Helper methods, which can be used in validator class
  1021. $.fn.bootstrapValidator.helpers = {
  1022. /**
  1023. * Validate a date
  1024. *
  1025. * @param {Number} year The full year in 4 digits
  1026. * @param {Number} month The month number
  1027. * @param {Number} day The day number
  1028. * @param {Boolean} [notInFuture] If true, the date must not be in the future
  1029. * @returns {Boolean}
  1030. */
  1031. date: function(year, month, day, notInFuture) {
  1032. if (isNaN(year) || isNaN(month) || isNaN(day)) {
  1033. return false;
  1034. }
  1035. if (year < 1000 || year > 9999 || month == 0 || month > 12) {
  1036. return false;
  1037. }
  1038. var numDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  1039. // Update the number of days in Feb of leap year
  1040. if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
  1041. numDays[1] = 29;
  1042. }
  1043. // Check the day
  1044. if (day < 0 || day > numDays[month - 1]) {
  1045. return false;
  1046. }
  1047. if (notInFuture === true) {
  1048. var currentDate = new Date(),
  1049. currentYear = currentDate.getFullYear(),
  1050. currentMonth = currentDate.getMonth(),
  1051. currentDay = currentDate.getDate();
  1052. return (year < currentYear
  1053. || (year == currentYear && month - 1 < currentMonth)
  1054. || (year == currentYear && month - 1 == currentMonth && day < currentDay));
  1055. }
  1056. return true;
  1057. },
  1058. /**
  1059. * Implement Luhn validation algorithm
  1060. * Credit to https://gist.github.com/ShirtlessKirk/2134376
  1061. *
  1062. * @see http://en.wikipedia.org/wiki/Luhn
  1063. * @param {String} value
  1064. * @returns {Boolean}
  1065. */
  1066. luhn: function(value) {
  1067. var length = value.length,
  1068. mul = 0,
  1069. prodArr = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]],
  1070. sum = 0;
  1071. while (length--) {
  1072. sum += prodArr[mul][parseInt(value.charAt(length), 10)];
  1073. mul ^= 1;
  1074. }
  1075. return (sum % 10 === 0 && sum > 0);
  1076. },
  1077. /**
  1078. * Implement modulus 11, 10 (ISO 7064) algorithm
  1079. *
  1080. * @param {String} value
  1081. * @returns {Boolean}
  1082. */
  1083. mod_11_10: function(value) {
  1084. var check = 5,
  1085. length = value.length;
  1086. for (var i = 0; i < length; i++) {
  1087. check = (((check || 10) * 2) % 11 + parseInt(value.charAt(i), 10)) % 10;
  1088. }
  1089. return (check == 1);
  1090. },
  1091. /**
  1092. * Implements Mod 37, 36 (ISO 7064) algorithm
  1093. * Usages:
  1094. * mod_37_36('A12425GABC1234002M')
  1095. * mod_37_36('002006673085', '0123456789')
  1096. *
  1097. * @param {String} value
  1098. * @param {String} alphabet
  1099. * @returns {Boolean}
  1100. */
  1101. mod_37_36: function(value, alphabet) {
  1102. alphabet = alphabet || '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  1103. var modulus = alphabet.length,
  1104. length = value.length,
  1105. check = Math.floor(modulus / 2);
  1106. for (var i = 0; i < length; i++) {
  1107. check = (((check || modulus) * 2) % (modulus + 1) + alphabet.indexOf(value.charAt(i))) % modulus;
  1108. }
  1109. return (check == 1);
  1110. }
  1111. };
  1112. }(window.jQuery));