bootstrapValidator.js 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003
  1. /**
  2. * BootstrapValidator (http://bootstrapvalidator.com)
  3. * The best jQuery plugin to validate form fields. Designed to use with Bootstrap 3
  4. *
  5. * @author https://twitter.com/nghuuphuoc
  6. * @copyright (c) 2013 - 2014 Nguyen Huu Phuoc
  7. * @license Commercial: http://bootstrapvalidator.com/license/
  8. * Non-commercial: http://creativecommons.org/licenses/by-nc-nd/3.0/
  9. */
  10. if (typeof jQuery === 'undefined') {
  11. throw new Error('BootstrapValidator requires jQuery');
  12. }
  13. (function($) {
  14. var version = $.fn.jquery.split(' ')[0].split('.');
  15. if ((+version[0] < 2 && +version[1] < 9) || (+version[0] === 1 && +version[1] === 9 && +version[2] < 1)) {
  16. throw new Error('BootstrapValidator requires jQuery version 1.9.1 or higher');
  17. }
  18. }(window.jQuery));
  19. (function($) {
  20. var BootstrapValidator = function(form, options) {
  21. this.$form = $(form);
  22. this.options = $.extend({}, $.fn.bootstrapValidator.DEFAULT_OPTIONS, options);
  23. this.$invalidFields = $([]); // Array of invalid fields
  24. this.$submitButton = null; // The submit button which is clicked to submit form
  25. this.$hiddenButton = null;
  26. // Validating status
  27. this.STATUS_NOT_VALIDATED = 'NOT_VALIDATED';
  28. this.STATUS_VALIDATING = 'VALIDATING';
  29. this.STATUS_INVALID = 'INVALID';
  30. this.STATUS_VALID = 'VALID';
  31. // Determine the event that is fired when user change the field value
  32. // Most modern browsers supports input event except IE 7, 8.
  33. // IE 9 supports input event but the event is still not fired if I press the backspace key.
  34. // Get IE version
  35. // https://gist.github.com/padolsey/527683/#comment-7595
  36. var ieVersion = (function() {
  37. var v = 3, div = document.createElement('div'), a = div.all || [];
  38. while (div.innerHTML = '<!--[if gt IE '+(++v)+']><br><![endif]-->', a[0]) {}
  39. return v > 4 ? v : !v;
  40. }());
  41. var el = document.createElement('div');
  42. this._changeEvent = (ieVersion === 9 || !('oninput' in el)) ? 'keyup' : 'input';
  43. // The flag to indicate that the form is ready to submit when a remote/callback validator returns
  44. this._submitIfValid = null;
  45. // Field elements
  46. this._cacheFields = {};
  47. this._init();
  48. };
  49. BootstrapValidator.prototype = {
  50. constructor: BootstrapValidator,
  51. /**
  52. * Init form
  53. */
  54. _init: function() {
  55. var that = this,
  56. options = {
  57. autoFocus: this.$form.attr('data-bv-autofocus'),
  58. container: this.$form.attr('data-bv-container'),
  59. events: {
  60. formInit: this.$form.attr('data-bv-events-form-init'),
  61. formError: this.$form.attr('data-bv-events-form-error'),
  62. formSuccess: this.$form.attr('data-bv-events-form-success'),
  63. fieldAdded: this.$form.attr('data-bv-events-field-added'),
  64. fieldRemoved: this.$form.attr('data-bv-events-field-removed'),
  65. fieldInit: this.$form.attr('data-bv-events-field-init'),
  66. fieldError: this.$form.attr('data-bv-events-field-error'),
  67. fieldSuccess: this.$form.attr('data-bv-events-field-success'),
  68. fieldStatus: this.$form.attr('data-bv-events-field-status'),
  69. validatorError: this.$form.attr('data-bv-events-validator-error'),
  70. validatorSuccess: this.$form.attr('data-bv-events-validator-success')
  71. },
  72. excluded: this.$form.attr('data-bv-excluded'),
  73. feedbackIcons: {
  74. valid: this.$form.attr('data-bv-feedbackicons-valid'),
  75. invalid: this.$form.attr('data-bv-feedbackicons-invalid'),
  76. validating: this.$form.attr('data-bv-feedbackicons-validating')
  77. },
  78. group: this.$form.attr('data-bv-group'),
  79. live: this.$form.attr('data-bv-live'),
  80. message: this.$form.attr('data-bv-message'),
  81. onError: this.$form.attr('data-bv-onerror'),
  82. onSuccess: this.$form.attr('data-bv-onsuccess'),
  83. submitButtons: this.$form.attr('data-bv-submitbuttons'),
  84. threshold: this.$form.attr('data-bv-threshold'),
  85. trigger: this.$form.attr('data-bv-trigger'),
  86. verbose: this.$form.attr('data-bv-verbose'),
  87. fields: {}
  88. };
  89. this.$form
  90. // Disable client side validation in HTML 5
  91. .attr('novalidate', 'novalidate')
  92. .addClass(this.options.elementClass)
  93. // Disable the default submission first
  94. .on('submit.bv', function(e) {
  95. e.preventDefault();
  96. that.validate();
  97. })
  98. .on('click.bv', this.options.submitButtons, function() {
  99. that.$submitButton = $(this);
  100. // The user just click the submit button
  101. that._submitIfValid = true;
  102. })
  103. // Find all fields which have either "name" or "data-bv-field" attribute
  104. .find('[name], [data-bv-field]')
  105. .each(function() {
  106. var $field = $(this),
  107. field = $field.attr('name') || $field.attr('data-bv-field'),
  108. opts = that._parseOptions($field);
  109. if (opts) {
  110. $field.attr('data-bv-field', field);
  111. options.fields[field] = $.extend({}, opts, options.fields[field]);
  112. }
  113. });
  114. this.options = $.extend(true, this.options, options);
  115. // When pressing Enter on any field in the form, the first submit button will do its job.
  116. // The form then will be submitted.
  117. // I create a first hidden submit button
  118. this.$hiddenButton = $('<button/>')
  119. .attr('type', 'submit')
  120. .prependTo(this.$form)
  121. .addClass('bv-hidden-submit')
  122. .css({ display: 'none', width: 0, height: 0 });
  123. this.$form
  124. .on('click.bv', '[type="submit"]', function(e) {
  125. // #746: Check if the button click handler returns false
  126. if (!e.isDefaultPrevented()) {
  127. var $target = $(e.target),
  128. // The button might contain HTML tag
  129. $button = $target.is('[type="submit"]') ? $target.eq(0) : $target.parent('[type="submit"]').eq(0);
  130. // Don't perform validation when clicking on the submit button/input
  131. // which aren't defined by the 'submitButtons' option
  132. if (that.options.submitButtons && !$button.is(that.options.submitButtons) && !$button.is(that.$hiddenButton)) {
  133. that.$form.off('submit.bv').submit();
  134. }
  135. }
  136. });
  137. for (var field in this.options.fields) {
  138. this._initField(field);
  139. }
  140. this.$form.trigger($.Event(this.options.events.formInit), {
  141. bv: this,
  142. options: this.options
  143. });
  144. // Prepare the events
  145. if (this.options.onSuccess) {
  146. this.$form.on(this.options.events.formSuccess, function(e) {
  147. $.fn.bootstrapValidator.helpers.call(that.options.onSuccess, [e]);
  148. });
  149. }
  150. if (this.options.onError) {
  151. this.$form.on(this.options.events.formError, function(e) {
  152. $.fn.bootstrapValidator.helpers.call(that.options.onError, [e]);
  153. });
  154. }
  155. },
  156. /**
  157. * Parse the validator options from HTML attributes
  158. *
  159. * @param {jQuery} $field The field element
  160. * @returns {Object}
  161. */
  162. _parseOptions: function($field) {
  163. var field = $field.attr('name') || $field.attr('data-bv-field'),
  164. validators = {},
  165. validator,
  166. v, // Validator name
  167. attrName,
  168. enabled,
  169. optionName,
  170. optionAttrName,
  171. optionValue,
  172. html5AttrName,
  173. html5AttrMap;
  174. for (v in $.fn.bootstrapValidator.validators) {
  175. validator = $.fn.bootstrapValidator.validators[v];
  176. attrName = 'data-bv-' + v.toLowerCase(),
  177. enabled = $field.attr(attrName) + '';
  178. html5AttrMap = ('function' === typeof validator.enableByHtml5) ? validator.enableByHtml5($field) : null;
  179. if ((html5AttrMap && enabled !== 'false')
  180. || (html5AttrMap !== true && ('' === enabled || 'true' === enabled || attrName === enabled.toLowerCase())))
  181. {
  182. // Try to parse the options via attributes
  183. validator.html5Attributes = $.extend({}, { message: 'message', onerror: 'onError', onsuccess: 'onSuccess' }, validator.html5Attributes);
  184. validators[v] = $.extend({}, html5AttrMap === true ? {} : html5AttrMap, validators[v]);
  185. for (html5AttrName in validator.html5Attributes) {
  186. optionName = validator.html5Attributes[html5AttrName];
  187. optionAttrName = 'data-bv-' + v.toLowerCase() + '-' + html5AttrName,
  188. optionValue = $field.attr(optionAttrName);
  189. if (optionValue) {
  190. if ('true' === optionValue || optionAttrName === optionValue.toLowerCase()) {
  191. optionValue = true;
  192. } else if ('false' === optionValue) {
  193. optionValue = false;
  194. }
  195. validators[v][optionName] = optionValue;
  196. }
  197. }
  198. }
  199. }
  200. var opts = {
  201. autoFocus: $field.attr('data-bv-autofocus'),
  202. container: $field.attr('data-bv-container'),
  203. excluded: $field.attr('data-bv-excluded'),
  204. feedbackIcons: $field.attr('data-bv-feedbackicons'),
  205. group: $field.attr('data-bv-group'),
  206. message: $field.attr('data-bv-message'),
  207. onError: $field.attr('data-bv-onerror'),
  208. onStatus: $field.attr('data-bv-onstatus'),
  209. onSuccess: $field.attr('data-bv-onsuccess'),
  210. selector: $field.attr('data-bv-selector'),
  211. threshold: $field.attr('data-bv-threshold'),
  212. trigger: $field.attr('data-bv-trigger'),
  213. verbose: $field.attr('data-bv-verbose'),
  214. validators: validators
  215. },
  216. emptyOptions = $.isEmptyObject(opts), // Check if the field options are set using HTML attributes
  217. emptyValidators = $.isEmptyObject(validators); // Check if the field validators are set using HTML attributes
  218. if (!emptyValidators || (!emptyOptions && this.options.fields && this.options.fields[field])) {
  219. opts.validators = validators;
  220. return opts;
  221. } else {
  222. return null;
  223. }
  224. },
  225. /**
  226. * Init field
  227. *
  228. * @param {String|jQuery} field The field name or field element
  229. */
  230. _initField: function(field) {
  231. var fields = $([]);
  232. switch (typeof field) {
  233. case 'object':
  234. fields = field;
  235. field = field.attr('data-bv-field');
  236. break;
  237. case 'string':
  238. fields = this.getFieldElements(field);
  239. fields.attr('data-bv-field', field);
  240. break;
  241. default:
  242. break;
  243. }
  244. // We don't need to validate non-existing fields
  245. if (fields.length === 0) {
  246. return;
  247. }
  248. if (this.options.fields[field] === null || this.options.fields[field].validators === null) {
  249. return;
  250. }
  251. var validatorName;
  252. for (validatorName in this.options.fields[field].validators) {
  253. if (!$.fn.bootstrapValidator.validators[validatorName]) {
  254. delete this.options.fields[field].validators[validatorName];
  255. }
  256. }
  257. if (this.options.fields[field].enabled === null) {
  258. this.options.fields[field].enabled = true;
  259. }
  260. var that = this,
  261. total = fields.length,
  262. type = fields.attr('type'),
  263. updateAll = (total === 1) || ('radio' === type) || ('checkbox' === type),
  264. event = ('radio' === type || 'checkbox' === type || 'file' === type || 'SELECT' === fields.eq(0).get(0).tagName) ? 'change' : this._changeEvent,
  265. trigger = (this.options.fields[field].trigger || this.options.trigger || event).split(' '),
  266. events = $.map(trigger, function(item) {
  267. return item + '.update.bv';
  268. }).join(' ');
  269. for (var i = 0; i < total; i++) {
  270. var $field = fields.eq(i),
  271. group = this.options.fields[field].group || this.options.group,
  272. $parent = $field.parents(group),
  273. // Allow user to indicate where the error messages are shown
  274. container = ('function' === typeof (this.options.fields[field].container || this.options.container)) ? (this.options.fields[field].container || this.options.container).call(this, $field, this) : (this.options.fields[field].container || this.options.container),
  275. $message = (container && container !== 'tooltip' && container !== 'popover') ? $(container) : this._getMessageContainer($field, group);
  276. if (container && container !== 'tooltip' && container !== 'popover') {
  277. $message.addClass('has-error');
  278. }
  279. // Remove all error messages and feedback icons
  280. $message.find('.help-block[data-bv-validator][data-bv-for="' + field + '"]').remove();
  281. $parent.find('i[data-bv-icon-for="' + field + '"]').remove();
  282. // Whenever the user change the field value, mark it as not validated yet
  283. $field.off(events).on(events, function() {
  284. that.updateStatus($(this), that.STATUS_NOT_VALIDATED);
  285. });
  286. // Create help block elements for showing the error messages
  287. $field.data('bv.messages', $message);
  288. for (validatorName in this.options.fields[field].validators) {
  289. $field.data('bv.result.' + validatorName, this.STATUS_NOT_VALIDATED);
  290. if (!updateAll || i === total - 1) {
  291. $('<small/>')
  292. .css('display', 'none')
  293. .addClass('help-block')
  294. .attr('data-bv-validator', validatorName)
  295. .attr('data-bv-for', field)
  296. .attr('data-bv-result', this.STATUS_NOT_VALIDATED)
  297. .html(this._getMessage(field, validatorName))
  298. .appendTo($message);
  299. }
  300. // Init the validator
  301. if ('function' === typeof $.fn.bootstrapValidator.validators[validatorName].init) {
  302. $.fn.bootstrapValidator.validators[validatorName].init(this, $field, this.options.fields[field].validators[validatorName]);
  303. }
  304. }
  305. // Prepare the feedback icons
  306. // Available from Bootstrap 3.1 (http://getbootstrap.com/css/#forms-control-validation)
  307. if (this.options.fields[field].feedbackIcons !== false && this.options.fields[field].feedbackIcons !== 'false'
  308. && this.options.feedbackIcons
  309. && this.options.feedbackIcons.validating && this.options.feedbackIcons.invalid && this.options.feedbackIcons.valid
  310. && (!updateAll || i === total - 1))
  311. {
  312. // $parent.removeClass('has-success').removeClass('has-error').addClass('has-feedback');
  313. // Keep error messages which are populated from back-end
  314. $parent.addClass('has-feedback');
  315. var $icon = $('<i/>')
  316. .css('display', 'none')
  317. .addClass('form-control-feedback')
  318. .attr('data-bv-icon-for', field)
  319. .insertAfter($field);
  320. // Place it after the container of checkbox/radio
  321. // so when clicking the icon, it doesn't effect to the checkbox/radio element
  322. if ('checkbox' === type || 'radio' === type) {
  323. var $fieldParent = $field.parent();
  324. if ($fieldParent.hasClass(type)) {
  325. $icon.insertAfter($fieldParent);
  326. } else if ($fieldParent.parent().hasClass(type)) {
  327. $icon.insertAfter($fieldParent.parent());
  328. }
  329. }
  330. // The feedback icon does not render correctly if there is no label
  331. // https://github.com/twbs/bootstrap/issues/12873
  332. if ($parent.find('label').length === 0) {
  333. $icon.addClass('bv-no-label');
  334. }
  335. // Fix feedback icons in input-group
  336. if ($parent.find('.input-group').length !== 0) {
  337. $icon.addClass('bv-icon-input-group')
  338. .insertAfter($parent.find('.input-group').eq(0));
  339. }
  340. // Store the icon as a data of field element
  341. if (!updateAll) {
  342. $field.data('bv.icon', $icon);
  343. } else if (i === total - 1) {
  344. // All fields with the same name have the same icon
  345. fields.data('bv.icon', $icon);
  346. }
  347. if (container) {
  348. $field
  349. // Show tooltip/popover message when field gets focus
  350. .off('focus.container.bv')
  351. .on('focus.container.bv', function() {
  352. switch (container) {
  353. case 'tooltip':
  354. $(this).data('bv.icon').tooltip('show');
  355. break;
  356. case 'popover':
  357. $(this).data('bv.icon').popover('show');
  358. break;
  359. default:
  360. break;
  361. }
  362. })
  363. // and hide them when losing focus
  364. .off('blur.container.bv')
  365. .on('blur.container.bv', function() {
  366. switch (container) {
  367. case 'tooltip':
  368. $(this).data('bv.icon').tooltip('hide');
  369. break;
  370. case 'popover':
  371. $(this).data('bv.icon').popover('hide');
  372. break;
  373. default:
  374. break;
  375. }
  376. });
  377. }
  378. }
  379. }
  380. // Prepare the events
  381. fields
  382. .on(this.options.events.fieldSuccess, function(e, data) {
  383. var onSuccess = that.getOptions(data.field, null, 'onSuccess');
  384. if (onSuccess) {
  385. $.fn.bootstrapValidator.helpers.call(onSuccess, [e, data]);
  386. }
  387. })
  388. .on(this.options.events.fieldError, function(e, data) {
  389. var onError = that.getOptions(data.field, null, 'onError');
  390. if (onError) {
  391. $.fn.bootstrapValidator.helpers.call(onError, [e, data]);
  392. }
  393. })
  394. .on(this.options.events.fieldStatus, function(e, data) {
  395. var onStatus = that.getOptions(data.field, null, 'onStatus');
  396. if (onStatus) {
  397. $.fn.bootstrapValidator.helpers.call(onStatus, [e, data]);
  398. }
  399. })
  400. .on(this.options.events.validatorError, function(e, data) {
  401. var onError = that.getOptions(data.field, data.validator, 'onError');
  402. if (onError) {
  403. $.fn.bootstrapValidator.helpers.call(onError, [e, data]);
  404. }
  405. })
  406. .on(this.options.events.validatorSuccess, function(e, data) {
  407. var onSuccess = that.getOptions(data.field, data.validator, 'onSuccess');
  408. if (onSuccess) {
  409. $.fn.bootstrapValidator.helpers.call(onSuccess, [e, data]);
  410. }
  411. });
  412. // Set live mode
  413. events = $.map(trigger, function(item) {
  414. return item + '.live.bv';
  415. }).join(' ');
  416. switch (this.options.live) {
  417. case 'submitted':
  418. break;
  419. case 'disabled':
  420. fields.off(events);
  421. break;
  422. case 'enabled':
  423. /* falls through */
  424. default:
  425. fields.off(events).on(events, function() {
  426. if (that._exceedThreshold($(this))) {
  427. that.validateField($(this));
  428. }
  429. });
  430. break;
  431. }
  432. fields.trigger($.Event(this.options.events.fieldInit), {
  433. bv: this,
  434. field: field,
  435. element: fields
  436. });
  437. },
  438. /**
  439. * Get the error message for given field and validator
  440. *
  441. * @param {String} field The field name
  442. * @param {String} validatorName The validator name
  443. * @returns {String}
  444. */
  445. _getMessage: function(field, validatorName) {
  446. if (!this.options.fields[field] || !$.fn.bootstrapValidator.validators[validatorName]
  447. || !this.options.fields[field].validators || !this.options.fields[field].validators[validatorName])
  448. {
  449. return '';
  450. }
  451. var options = this.options.fields[field].validators[validatorName];
  452. switch (true) {
  453. case (!!options.message):
  454. return options.message;
  455. case (!!this.options.fields[field].message):
  456. return this.options.fields[field].message;
  457. case (!!$.fn.bootstrapValidator.i18n[validatorName]):
  458. return $.fn.bootstrapValidator.i18n[validatorName]['default'];
  459. default:
  460. return this.options.message;
  461. }
  462. },
  463. /**
  464. * Get the element to place the error messages
  465. *
  466. * @param {jQuery} $field The field element
  467. * @param {String} group
  468. * @returns {jQuery}
  469. */
  470. _getMessageContainer: function($field, group) {
  471. var $parent = $field.parent();
  472. if ($parent.is(group)) {
  473. return $parent;
  474. }
  475. var cssClasses = $parent.attr('class');
  476. if (!cssClasses) {
  477. return this._getMessageContainer($parent, group);
  478. }
  479. cssClasses = cssClasses.split(' ');
  480. var n = cssClasses.length;
  481. for (var i = 0; i < n; i++) {
  482. if (/^col-(xs|sm|md|lg)-\d+$/.test(cssClasses[i]) || /^col-(xs|sm|md|lg)-offset-\d+$/.test(cssClasses[i])) {
  483. return $parent;
  484. }
  485. }
  486. return this._getMessageContainer($parent, group);
  487. },
  488. /**
  489. * Called when all validations are completed
  490. */
  491. _submit: function() {
  492. var isValid = this.isValid(),
  493. eventType = isValid ? this.options.events.formSuccess : this.options.events.formError,
  494. e = $.Event(eventType);
  495. this.$form.trigger(e);
  496. // Call default handler
  497. // Check if whether the submit button is clicked
  498. if (this.$submitButton) {
  499. isValid ? this._onSuccess(e) : this._onError(e);
  500. }
  501. },
  502. /**
  503. * Check if the field is excluded.
  504. * Returning true means that the field will not be validated
  505. *
  506. * @param {jQuery} $field The field element
  507. * @returns {Boolean}
  508. */
  509. _isExcluded: function($field) {
  510. var excludedAttr = $field.attr('data-bv-excluded'),
  511. // I still need to check the 'name' attribute while initializing the field
  512. field = $field.attr('data-bv-field') || $field.attr('name');
  513. switch (true) {
  514. case (!!field && this.options.fields && this.options.fields[field] && (this.options.fields[field].excluded === 'true' || this.options.fields[field].excluded === true)):
  515. case (excludedAttr === 'true'):
  516. case (excludedAttr === ''):
  517. return true;
  518. case (!!field && this.options.fields && this.options.fields[field] && (this.options.fields[field].excluded === 'false' || this.options.fields[field].excluded === false)):
  519. case (excludedAttr === 'false'):
  520. return false;
  521. default:
  522. if (this.options.excluded) {
  523. // Convert to array first
  524. if ('string' === typeof this.options.excluded) {
  525. this.options.excluded = $.map(this.options.excluded.split(','), function(item) {
  526. // Trim the spaces
  527. return $.trim(item);
  528. });
  529. }
  530. var length = this.options.excluded.length;
  531. for (var i = 0; i < length; i++) {
  532. if (('string' === typeof this.options.excluded[i] && $field.is(this.options.excluded[i]))
  533. || ('function' === typeof this.options.excluded[i] && this.options.excluded[i].call(this, $field, this) === true))
  534. {
  535. return true;
  536. }
  537. }
  538. }
  539. return false;
  540. }
  541. },
  542. /**
  543. * Check if the number of characters of field value exceed the threshold or not
  544. *
  545. * @param {jQuery} $field The field element
  546. * @returns {Boolean}
  547. */
  548. _exceedThreshold: function($field) {
  549. var field = $field.attr('data-bv-field'),
  550. threshold = this.options.fields[field].threshold || this.options.threshold;
  551. if (!threshold) {
  552. return true;
  553. }
  554. var cannotType = $.inArray($field.attr('type'), ['button', 'checkbox', 'file', 'hidden', 'image', 'radio', 'reset', 'submit']) !== -1;
  555. return (cannotType || $field.val().length >= threshold);
  556. },
  557. // ---
  558. // Events
  559. // ---
  560. /**
  561. * The default handler of error.form.bv event.
  562. * It will be called when there is a invalid field
  563. *
  564. * @param {jQuery.Event} e The jQuery event object
  565. */
  566. _onError: function(e) {
  567. if (e.isDefaultPrevented()) {
  568. return;
  569. }
  570. if ('submitted' === this.options.live) {
  571. // Enable live mode
  572. this.options.live = 'enabled';
  573. var that = this;
  574. for (var field in this.options.fields) {
  575. (function(f) {
  576. var fields = that.getFieldElements(f);
  577. if (fields.length) {
  578. var type = $(fields[0]).attr('type'),
  579. event = ('radio' === type || 'checkbox' === type || 'file' === type || 'SELECT' === $(fields[0]).get(0).tagName) ? 'change' : that._changeEvent,
  580. trigger = that.options.fields[field].trigger || that.options.trigger || event,
  581. events = $.map(trigger.split(' '), function(item) {
  582. return item + '.live.bv';
  583. }).join(' ');
  584. fields.off(events).on(events, function() {
  585. if (that._exceedThreshold($(this))) {
  586. that.validateField($(this));
  587. }
  588. });
  589. }
  590. })(field);
  591. }
  592. }
  593. // Determined the first invalid field which will be focused on automatically
  594. for (var i = 0; i < this.$invalidFields.length; i++) {
  595. var $field = this.$invalidFields.eq(i),
  596. autoFocus = this._isOptionEnabled($field.attr('data-bv-field'), 'autoFocus');
  597. if (autoFocus) {
  598. // Activate the tab containing the field if exists
  599. var $tabPane = $field.parents('.tab-pane'), tabId;
  600. if ($tabPane && (tabId = $tabPane.attr('id'))) {
  601. $('a[href="#' + tabId + '"][data-toggle="tab"]').tab('show');
  602. }
  603. // Focus the field
  604. $field.focus();
  605. break;
  606. }
  607. }
  608. },
  609. /**
  610. * The default handler of success.form.bv event.
  611. * It will be called when all the fields are valid
  612. *
  613. * @param {jQuery.Event} e The jQuery event object
  614. */
  615. _onSuccess: function(e) {
  616. if (e.isDefaultPrevented()) {
  617. return;
  618. }
  619. // Submit the form
  620. this.disableSubmitButtons(true).defaultSubmit();
  621. },
  622. /**
  623. * Called after validating a field element
  624. *
  625. * @param {jQuery} $field The field element
  626. * @param {String} [validatorName] The validator name
  627. */
  628. _onFieldValidated: function($field, validatorName) {
  629. var field = $field.attr('data-bv-field'),
  630. validators = this.options.fields[field].validators,
  631. counter = {},
  632. numValidators = 0,
  633. data = {
  634. bv: this,
  635. field: field,
  636. element: $field,
  637. validator: validatorName,
  638. result: $field.data('bv.response.' + validatorName)
  639. };
  640. // Trigger an event after given validator completes
  641. if (validatorName) {
  642. switch ($field.data('bv.result.' + validatorName)) {
  643. case this.STATUS_INVALID:
  644. $field.trigger($.Event(this.options.events.validatorError), data);
  645. break;
  646. case this.STATUS_VALID:
  647. $field.trigger($.Event(this.options.events.validatorSuccess), data);
  648. break;
  649. default:
  650. break;
  651. }
  652. }
  653. counter[this.STATUS_NOT_VALIDATED] = 0;
  654. counter[this.STATUS_VALIDATING] = 0;
  655. counter[this.STATUS_INVALID] = 0;
  656. counter[this.STATUS_VALID] = 0;
  657. for (var v in validators) {
  658. if (validators[v].enabled === false) {
  659. continue;
  660. }
  661. numValidators++;
  662. var result = $field.data('bv.result.' + v);
  663. if (result) {
  664. counter[result]++;
  665. }
  666. }
  667. if (counter[this.STATUS_VALID] === numValidators) {
  668. // Remove from the list of invalid fields
  669. this.$invalidFields = this.$invalidFields.not($field);
  670. $field.trigger($.Event(this.options.events.fieldSuccess), data);
  671. }
  672. // If all validators are completed and there is at least one validator which doesn't pass
  673. else if ((counter[this.STATUS_NOT_VALIDATED] === 0 || !this._isOptionEnabled(field, 'verbose')) && counter[this.STATUS_VALIDATING] === 0 && counter[this.STATUS_INVALID] > 0) {
  674. // Add to the list of invalid fields
  675. this.$invalidFields = this.$invalidFields.add($field);
  676. $field.trigger($.Event(this.options.events.fieldError), data);
  677. }
  678. },
  679. /**
  680. * Check whether or not a field option is enabled
  681. *
  682. * @param {String} field The field name
  683. * @param {String} option The option name, "verbose", "autoFocus", for example
  684. * @returns {Boolean}
  685. */
  686. _isOptionEnabled: function(field, option) {
  687. if (this.options.fields[field] && (this.options.fields[field][option] === 'true' || this.options.fields[field][option] === true)) {
  688. return true;
  689. }
  690. if (this.options.fields[field] && (this.options.fields[field][option] === 'false' || this.options.fields[field][option] === false)) {
  691. return false;
  692. }
  693. return this.options[option] === 'true' || this.options[option] === true;
  694. },
  695. // ---
  696. // Public methods
  697. // ---
  698. /**
  699. * Retrieve the field elements by given name
  700. *
  701. * @param {String} field The field name
  702. * @returns {null|jQuery[]}
  703. */
  704. getFieldElements: function(field) {
  705. if (!this._cacheFields[field]) {
  706. this._cacheFields[field] = (this.options.fields[field] && this.options.fields[field].selector)
  707. ? $(this.options.fields[field].selector)
  708. : this.$form.find('[name="' + field + '"]');
  709. }
  710. return this._cacheFields[field];
  711. },
  712. /**
  713. * Get the field options
  714. *
  715. * @param {String|jQuery} [field] The field name or field element. If it is not set, the method returns the form options
  716. * @param {String} [validator] The name of validator. It null, the method returns form options
  717. * @param {String} [option] The option name
  718. * @return {String|Object}
  719. */
  720. getOptions: function(field, validator, option) {
  721. if (!field) {
  722. return option ? this.options[option] : this.options;
  723. }
  724. if ('object' === typeof field) {
  725. field = field.attr('data-bv-field');
  726. }
  727. if (!this.options.fields[field]) {
  728. return null;
  729. }
  730. var options = this.options.fields[field];
  731. if (!validator) {
  732. return option ? options[option] : options;
  733. }
  734. if (!options.validators || !options.validators[validator]) {
  735. return null;
  736. }
  737. return option ? options.validators[validator][option] : options.validators[validator];
  738. },
  739. /**
  740. * Disable/enable submit buttons
  741. *
  742. * @param {Boolean} disabled Can be true or false
  743. * @returns {BootstrapValidator}
  744. */
  745. disableSubmitButtons: function(disabled) {
  746. if (!disabled) {
  747. this.$form.find(this.options.submitButtons).removeAttr('disabled');
  748. } else if (this.options.live !== 'disabled') {
  749. // Don't disable if the live validating mode is disabled
  750. this.$form.find(this.options.submitButtons).attr('disabled', 'disabled');
  751. }
  752. return this;
  753. },
  754. /**
  755. * Validate the form
  756. *
  757. * @returns {BootstrapValidator}
  758. */
  759. validate: function() {
  760. if (!this.options.fields) {
  761. return this;
  762. }
  763. this.disableSubmitButtons(true);
  764. this._submitIfValid = false;
  765. for (var field in this.options.fields) {
  766. this.validateField(field);
  767. }
  768. this._submit();
  769. this._submitIfValid = true;
  770. return this;
  771. },
  772. /**
  773. * Validate given field
  774. *
  775. * @param {String|jQuery} field The field name or field element
  776. * @returns {BootstrapValidator}
  777. */
  778. validateField: function(field) {
  779. var fields = $([]);
  780. switch (typeof field) {
  781. case 'object':
  782. fields = field;
  783. field = field.attr('data-bv-field');
  784. break;
  785. case 'string':
  786. fields = this.getFieldElements(field);
  787. break;
  788. default:
  789. break;
  790. }
  791. if (fields.length === 0 || !this.options.fields[field] || this.options.fields[field].enabled === false) {
  792. return this;
  793. }
  794. var that = this,
  795. type = fields.attr('type'),
  796. total = ('radio' === type || 'checkbox' === type) ? 1 : fields.length,
  797. updateAll = ('radio' === type || 'checkbox' === type),
  798. validators = this.options.fields[field].validators,
  799. verbose = this._isOptionEnabled(field, 'verbose'),
  800. validatorName,
  801. validateResult;
  802. for (var i = 0; i < total; i++) {
  803. var $field = fields.eq(i);
  804. if (this._isExcluded($field)) {
  805. continue;
  806. }
  807. var stop = false;
  808. for (validatorName in validators) {
  809. if ($field.data('bv.dfs.' + validatorName)) {
  810. $field.data('bv.dfs.' + validatorName).reject();
  811. }
  812. if (stop) {
  813. break;
  814. }
  815. // Don't validate field if it is already done
  816. var result = $field.data('bv.result.' + validatorName);
  817. if (result === this.STATUS_VALID || result === this.STATUS_INVALID) {
  818. this._onFieldValidated($field, validatorName);
  819. continue;
  820. } else if (validators[validatorName].enabled === false) {
  821. this.updateStatus(updateAll ? field : $field, this.STATUS_VALID, validatorName);
  822. continue;
  823. }
  824. $field.data('bv.result.' + validatorName, this.STATUS_VALIDATING);
  825. validateResult = $.fn.bootstrapValidator.validators[validatorName].validate(this, $field, validators[validatorName]);
  826. // validateResult can be a $.Deferred object ...
  827. if ('object' === typeof validateResult && validateResult.resolve) {
  828. this.updateStatus(updateAll ? field : $field, this.STATUS_VALIDATING, validatorName);
  829. $field.data('bv.dfs.' + validatorName, validateResult);
  830. validateResult.done(function($f, v, response) {
  831. // v is validator name
  832. $f.removeData('bv.dfs.' + v).data('bv.response.' + v, response);
  833. if (response.message) {
  834. that.updateMessage($f, v, response.message);
  835. }
  836. that.updateStatus(updateAll ? $f.attr('data-bv-field') : $f, response.valid ? that.STATUS_VALID : that.STATUS_INVALID, v);
  837. if (response.valid && that._submitIfValid === true) {
  838. // If a remote validator returns true and the form is ready to submit, then do it
  839. that._submit();
  840. } else if (!response.valid && !verbose) {
  841. stop = true;
  842. }
  843. });
  844. }
  845. // ... or object { valid: true/false, message: 'dynamic message' }
  846. else if ('object' === typeof validateResult && validateResult.valid !== undefined && validateResult.message !== undefined) {
  847. $field.data('bv.response.' + validatorName, validateResult);
  848. this.updateMessage(updateAll ? field : $field, validatorName, validateResult.message);
  849. this.updateStatus(updateAll ? field : $field, validateResult.valid ? this.STATUS_VALID : this.STATUS_INVALID, validatorName);
  850. if (!validateResult.valid && !verbose) {
  851. break;
  852. }
  853. }
  854. // ... or a boolean value
  855. else if ('boolean' === typeof validateResult) {
  856. $field.data('bv.response.' + validatorName, validateResult);
  857. this.updateStatus(updateAll ? field : $field, validateResult ? this.STATUS_VALID : this.STATUS_INVALID, validatorName);
  858. if (!validateResult && !verbose) {
  859. break;
  860. }
  861. }
  862. }
  863. }
  864. return this;
  865. },
  866. /**
  867. * Update the error message
  868. *
  869. * @param {String|jQuery} field The field name or field element
  870. * @param {String} validator The validator name
  871. * @param {String} message The message
  872. * @returns {BootstrapValidator}
  873. */
  874. updateMessage: function(field, validator, message) {
  875. var $fields = $([]);
  876. switch (typeof field) {
  877. case 'object':
  878. $fields = field;
  879. field = field.attr('data-bv-field');
  880. break;
  881. case 'string':
  882. $fields = this.getFieldElements(field);
  883. break;
  884. default:
  885. break;
  886. }
  887. $fields.each(function() {
  888. $(this).data('bv.messages').find('.help-block[data-bv-validator="' + validator + '"][data-bv-for="' + field + '"]').html(message);
  889. });
  890. },
  891. /**
  892. * Update all validating results of field
  893. *
  894. * @param {String|jQuery} field The field name or field element
  895. * @param {String} status The status. Can be 'NOT_VALIDATED', 'VALIDATING', 'INVALID' or 'VALID'
  896. * @param {String} [validatorName] The validator name. If null, the method updates validity result for all validators
  897. * @returns {BootstrapValidator}
  898. */
  899. updateStatus: function(field, status, validatorName) {
  900. var fields = $([]);
  901. switch (typeof field) {
  902. case 'object':
  903. fields = field;
  904. field = field.attr('data-bv-field');
  905. break;
  906. case 'string':
  907. fields = this.getFieldElements(field);
  908. break;
  909. default:
  910. break;
  911. }
  912. if (status === this.STATUS_NOT_VALIDATED) {
  913. // Reset the flag
  914. // To prevent the form from doing submit when a deferred validator returns true while typing
  915. this._submitIfValid = false;
  916. }
  917. var that = this,
  918. type = fields.attr('type'),
  919. group = this.options.fields[field].group || this.options.group,
  920. total = ('radio' === type || 'checkbox' === type) ? 1 : fields.length;
  921. for (var i = 0; i < total; i++) {
  922. var $field = fields.eq(i);
  923. if (this._isExcluded($field)) {
  924. continue;
  925. }
  926. var $parent = $field.parents(group),
  927. $message = $field.data('bv.messages'),
  928. $allErrors = $message.find('.help-block[data-bv-validator][data-bv-for="' + field + '"]'),
  929. $errors = validatorName ? $allErrors.filter('[data-bv-validator="' + validatorName + '"]') : $allErrors,
  930. $icon = $field.data('bv.icon'),
  931. container = ('function' === typeof (this.options.fields[field].container || this.options.container)) ? (this.options.fields[field].container || this.options.container).call(this, $field, this) : (this.options.fields[field].container || this.options.container),
  932. isValidField = null;
  933. // Update status
  934. if (validatorName) {
  935. $field.data('bv.result.' + validatorName, status);
  936. } else {
  937. for (var v in this.options.fields[field].validators) {
  938. $field.data('bv.result.' + v, status);
  939. }
  940. }
  941. // Show/hide error elements and feedback icons
  942. $errors.attr('data-bv-result', status);
  943. // Determine the tab containing the element
  944. var $tabPane = $field.parents('.tab-pane'),
  945. tabId, $tab;
  946. if ($tabPane && (tabId = $tabPane.attr('id'))) {
  947. $tab = $('a[href="#' + tabId + '"][data-toggle="tab"]').parent();
  948. }
  949. switch (status) {
  950. case this.STATUS_VALIDATING:
  951. isValidField = null;
  952. this.disableSubmitButtons(true);
  953. $parent.removeClass('has-success').removeClass('has-error');
  954. if ($icon) {
  955. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).addClass(this.options.feedbackIcons.validating).show();
  956. }
  957. if ($tab) {
  958. $tab.removeClass('bv-tab-success').removeClass('bv-tab-error');
  959. }
  960. break;
  961. case this.STATUS_INVALID:
  962. isValidField = false;
  963. this.disableSubmitButtons(true);
  964. $parent.removeClass('has-success').addClass('has-error');
  965. if ($icon) {
  966. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.validating).addClass(this.options.feedbackIcons.invalid).show();
  967. }
  968. if ($tab) {
  969. $tab.removeClass('bv-tab-success').addClass('bv-tab-error');
  970. }
  971. break;
  972. case this.STATUS_VALID:
  973. // If the field is valid (passes all validators)
  974. isValidField = ($allErrors.filter('[data-bv-result="' + this.STATUS_NOT_VALIDATED +'"]').length === 0)
  975. ? ($allErrors.filter('[data-bv-result="' + this.STATUS_VALID +'"]').length === $allErrors.length) // All validators are completed
  976. : null; // There are some validators that have not done
  977. if (isValidField !== null) {
  978. this.disableSubmitButtons(this.$submitButton ? !this.isValid() : !isValidField);
  979. if ($icon) {
  980. $icon
  981. .removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).removeClass(this.options.feedbackIcons.valid)
  982. .addClass(isValidField ? this.options.feedbackIcons.valid : this.options.feedbackIcons.invalid)
  983. .show();
  984. }
  985. }
  986. $parent.removeClass('has-error has-success').addClass(this.isValidContainer($parent) ? 'has-success' : 'has-error');
  987. if ($tab) {
  988. $tab.removeClass('bv-tab-success').removeClass('bv-tab-error').addClass(this.isValidContainer($tabPane) ? 'bv-tab-success' : 'bv-tab-error');
  989. }
  990. break;
  991. case this.STATUS_NOT_VALIDATED:
  992. /* falls through */
  993. default:
  994. isValidField = null;
  995. this.disableSubmitButtons(false);
  996. $parent.removeClass('has-success').removeClass('has-error');
  997. if ($icon) {
  998. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).hide();
  999. }
  1000. if ($tab) {
  1001. $tab.removeClass('bv-tab-success').removeClass('bv-tab-error');
  1002. }
  1003. break;
  1004. }
  1005. switch (true) {
  1006. // Only show the first error message if it is placed inside a tooltip ...
  1007. case ($icon && 'tooltip' === container):
  1008. (isValidField === false)
  1009. ? $icon.css('cursor', 'pointer').tooltip('destroy').tooltip({
  1010. container: 'body',
  1011. html: true,
  1012. placement: 'auto top',
  1013. title: $allErrors.filter('[data-bv-result="' + that.STATUS_INVALID + '"]').eq(0).html()
  1014. })
  1015. : $icon.css('cursor', '').tooltip('destroy');
  1016. break;
  1017. // ... or popover
  1018. case ($icon && 'popover' === container):
  1019. (isValidField === false)
  1020. ? $icon.css('cursor', 'pointer').popover('destroy').popover({
  1021. container: 'body',
  1022. content: $allErrors.filter('[data-bv-result="' + that.STATUS_INVALID + '"]').eq(0).html(),
  1023. html: true,
  1024. placement: 'auto top',
  1025. trigger: 'hover click'
  1026. })
  1027. : $icon.css('cursor', '').popover('destroy');
  1028. break;
  1029. default:
  1030. (status === this.STATUS_INVALID) ? $errors.show() : $errors.hide();
  1031. break;
  1032. }
  1033. // Trigger an event
  1034. $field.trigger($.Event(this.options.events.fieldStatus), {
  1035. bv: this,
  1036. field: field,
  1037. element: $field,
  1038. status: status
  1039. });
  1040. this._onFieldValidated($field, validatorName);
  1041. }
  1042. return this;
  1043. },
  1044. /**
  1045. * Check the form validity
  1046. *
  1047. * @returns {Boolean}
  1048. */
  1049. isValid: function() {
  1050. for (var field in this.options.fields) {
  1051. if (!this.isValidField(field)) {
  1052. return false;
  1053. }
  1054. }
  1055. return true;
  1056. },
  1057. /**
  1058. * Check if the field is valid or not
  1059. *
  1060. * @param {String|jQuery} field The field name or field element
  1061. * @returns {Boolean}
  1062. */
  1063. isValidField: function(field) {
  1064. var fields = $([]);
  1065. switch (typeof field) {
  1066. case 'object':
  1067. fields = field;
  1068. field = field.attr('data-bv-field');
  1069. break;
  1070. case 'string':
  1071. fields = this.getFieldElements(field);
  1072. break;
  1073. default:
  1074. break;
  1075. }
  1076. if (fields.length === 0 || !this.options.fields[field] || this.options.fields[field].enabled === false) {
  1077. return true;
  1078. }
  1079. var type = fields.attr('type'),
  1080. total = ('radio' === type || 'checkbox' === type) ? 1 : fields.length,
  1081. $field, validatorName, status;
  1082. for (var i = 0; i < total; i++) {
  1083. $field = fields.eq(i);
  1084. if (this._isExcluded($field)) {
  1085. continue;
  1086. }
  1087. for (validatorName in this.options.fields[field].validators) {
  1088. if (this.options.fields[field].validators[validatorName].enabled === false) {
  1089. continue;
  1090. }
  1091. status = $field.data('bv.result.' + validatorName);
  1092. if (status !== this.STATUS_VALID) {
  1093. return false;
  1094. }
  1095. }
  1096. }
  1097. return true;
  1098. },
  1099. /**
  1100. * Check if all fields inside a given container are valid.
  1101. * It's useful when working with a wizard-like such as tab, collapse
  1102. *
  1103. * @param {String|jQuery} container The container selector or element
  1104. * @returns {Boolean}
  1105. */
  1106. isValidContainer: function(container) {
  1107. var that = this,
  1108. map = {},
  1109. $container = ('string' === typeof container) ? $(container) : container;
  1110. if ($container.length === 0) {
  1111. return true;
  1112. }
  1113. $container.find('[data-bv-field]').each(function() {
  1114. var $field = $(this),
  1115. field = $field.attr('data-bv-field');
  1116. if (!that._isExcluded($field) && !map[field]) {
  1117. map[field] = $field;
  1118. }
  1119. });
  1120. for (var field in map) {
  1121. var $f = map[field];
  1122. if ($f.data('bv.messages')
  1123. .find('.help-block[data-bv-validator][data-bv-for="' + field + '"]')
  1124. .filter('[data-bv-result="' + this.STATUS_INVALID +'"]')
  1125. .length > 0)
  1126. {
  1127. return false;
  1128. }
  1129. }
  1130. return true;
  1131. },
  1132. /**
  1133. * Submit the form using default submission.
  1134. * It also does not perform any validations when submitting the form
  1135. */
  1136. defaultSubmit: function() {
  1137. if (this.$submitButton) {
  1138. // Create hidden input to send the submit buttons
  1139. $('<input/>')
  1140. .attr('type', 'hidden')
  1141. .attr('data-bv-submit-hidden', '')
  1142. .attr('name', this.$submitButton.attr('name'))
  1143. .val(this.$submitButton.val())
  1144. .appendTo(this.$form);
  1145. }
  1146. // Submit form
  1147. this.$form.off('submit.bv').submit();
  1148. },
  1149. // ---
  1150. // Useful APIs which aren't used internally
  1151. // ---
  1152. /**
  1153. * Get the list of invalid fields
  1154. *
  1155. * @returns {jQuery[]}
  1156. */
  1157. getInvalidFields: function() {
  1158. return this.$invalidFields;
  1159. },
  1160. /**
  1161. * Returns the clicked submit button
  1162. *
  1163. * @returns {jQuery}
  1164. */
  1165. getSubmitButton: function() {
  1166. return this.$submitButton;
  1167. },
  1168. /**
  1169. * Get the error messages
  1170. *
  1171. * @param {String|jQuery} [field] The field name or field element
  1172. * If the field is not defined, the method returns all error messages of all fields
  1173. * @param {String} [validator] The name of validator
  1174. * If the validator is not defined, the method returns error messages of all validators
  1175. * @returns {String[]}
  1176. */
  1177. getMessages: function(field, validator) {
  1178. var that = this,
  1179. messages = [],
  1180. $fields = $([]);
  1181. switch (true) {
  1182. case (field && 'object' === typeof field):
  1183. $fields = field;
  1184. break;
  1185. case (field && 'string' === typeof field):
  1186. var f = this.getFieldElements(field);
  1187. if (f.length > 0) {
  1188. var type = f.attr('type');
  1189. $fields = ('radio' === type || 'checkbox' === type) ? f.eq(0) : f;
  1190. }
  1191. break;
  1192. default:
  1193. $fields = this.$invalidFields;
  1194. break;
  1195. }
  1196. var filter = validator ? '[data-bv-validator="' + validator + '"]' : '';
  1197. $fields.each(function() {
  1198. messages = messages.concat(
  1199. $(this)
  1200. .data('bv.messages')
  1201. .find('.help-block[data-bv-for="' + $(this).attr('data-bv-field') + '"][data-bv-result="' + that.STATUS_INVALID + '"]' + filter)
  1202. .map(function() {
  1203. var v = $(this).attr('data-bv-validator'),
  1204. f = $(this).attr('data-bv-for');
  1205. return (that.options.fields[f].validators[v].enabled === false) ? '' : $(this).html();
  1206. })
  1207. .get()
  1208. );
  1209. });
  1210. return messages;
  1211. },
  1212. /**
  1213. * Update the option of a specific validator
  1214. *
  1215. * @param {String|jQuery} field The field name or field element
  1216. * @param {String} validator The validator name
  1217. * @param {String} option The option name
  1218. * @param {String} value The value to set
  1219. * @returns {BootstrapValidator}
  1220. */
  1221. updateOption: function(field, validator, option, value) {
  1222. if ('object' === typeof field) {
  1223. field = field.attr('data-bv-field');
  1224. }
  1225. if (this.options.fields[field] && this.options.fields[field].validators[validator]) {
  1226. this.options.fields[field].validators[validator][option] = value;
  1227. this.updateStatus(field, this.STATUS_NOT_VALIDATED, validator);
  1228. }
  1229. return this;
  1230. },
  1231. /**
  1232. * Add a new field
  1233. *
  1234. * @param {String|jQuery} field The field name or field element
  1235. * @param {Object} [options] The validator rules
  1236. * @returns {BootstrapValidator}
  1237. */
  1238. addField: function(field, options) {
  1239. var fields = $([]);
  1240. switch (typeof field) {
  1241. case 'object':
  1242. fields = field;
  1243. field = field.attr('data-bv-field') || field.attr('name');
  1244. break;
  1245. case 'string':
  1246. delete this._cacheFields[field];
  1247. fields = this.getFieldElements(field);
  1248. break;
  1249. default:
  1250. break;
  1251. }
  1252. fields.attr('data-bv-field', field);
  1253. var type = fields.attr('type'),
  1254. total = ('radio' === type || 'checkbox' === type) ? 1 : fields.length;
  1255. for (var i = 0; i < total; i++) {
  1256. var $field = fields.eq(i);
  1257. // Try to parse the options from HTML attributes
  1258. var opts = this._parseOptions($field);
  1259. opts = (opts === null) ? options : $.extend(true, options, opts);
  1260. this.options.fields[field] = $.extend(true, this.options.fields[field], opts);
  1261. // Update the cache
  1262. this._cacheFields[field] = this._cacheFields[field] ? this._cacheFields[field].add($field) : $field;
  1263. // Init the element
  1264. this._initField(('checkbox' === type || 'radio' === type) ? field : $field);
  1265. }
  1266. this.disableSubmitButtons(false);
  1267. // Trigger an event
  1268. this.$form.trigger($.Event(this.options.events.fieldAdded), {
  1269. field: field,
  1270. element: fields,
  1271. options: this.options.fields[field]
  1272. });
  1273. return this;
  1274. },
  1275. /**
  1276. * Remove a given field
  1277. *
  1278. * @param {String|jQuery} field The field name or field element
  1279. * @returns {BootstrapValidator}
  1280. */
  1281. removeField: function(field) {
  1282. var fields = $([]);
  1283. switch (typeof field) {
  1284. case 'object':
  1285. fields = field;
  1286. field = field.attr('data-bv-field') || field.attr('name');
  1287. fields.attr('data-bv-field', field);
  1288. break;
  1289. case 'string':
  1290. fields = this.getFieldElements(field);
  1291. break;
  1292. default:
  1293. break;
  1294. }
  1295. if (fields.length === 0) {
  1296. return this;
  1297. }
  1298. var type = fields.attr('type'),
  1299. total = ('radio' === type || 'checkbox' === type) ? 1 : fields.length;
  1300. for (var i = 0; i < total; i++) {
  1301. var $field = fields.eq(i);
  1302. // Remove from the list of invalid fields
  1303. this.$invalidFields = this.$invalidFields.not($field);
  1304. // Update the cache
  1305. this._cacheFields[field] = this._cacheFields[field].not($field);
  1306. }
  1307. if (!this._cacheFields[field] || this._cacheFields[field].length === 0) {
  1308. delete this.options.fields[field];
  1309. }
  1310. if ('checkbox' === type || 'radio' === type) {
  1311. this._initField(field);
  1312. }
  1313. this.disableSubmitButtons(false);
  1314. // Trigger an event
  1315. this.$form.trigger($.Event(this.options.events.fieldRemoved), {
  1316. field: field,
  1317. element: fields
  1318. });
  1319. return this;
  1320. },
  1321. /**
  1322. * Reset given field
  1323. *
  1324. * @param {String|jQuery} field The field name or field element
  1325. * @param {Boolean} [resetValue] If true, the method resets field value to empty or remove checked/selected attribute (for radio/checkbox)
  1326. * @returns {BootstrapValidator}
  1327. */
  1328. resetField: function(field, resetValue) {
  1329. var $fields = $([]);
  1330. switch (typeof field) {
  1331. case 'object':
  1332. $fields = field;
  1333. field = field.attr('data-bv-field');
  1334. break;
  1335. case 'string':
  1336. $fields = this.getFieldElements(field);
  1337. break;
  1338. default:
  1339. break;
  1340. }
  1341. var total = $fields.length;
  1342. if (this.options.fields[field]) {
  1343. for (var i = 0; i < total; i++) {
  1344. for (var validator in this.options.fields[field].validators) {
  1345. $fields.eq(i).removeData('bv.dfs.' + validator);
  1346. }
  1347. }
  1348. }
  1349. // Mark field as not validated yet
  1350. this.updateStatus(field, this.STATUS_NOT_VALIDATED);
  1351. if (resetValue) {
  1352. var type = $fields.attr('type');
  1353. ('radio' === type || 'checkbox' === type) ? $fields.removeAttr('checked').removeAttr('selected') : $fields.val('');
  1354. }
  1355. return this;
  1356. },
  1357. /**
  1358. * Reset the form
  1359. *
  1360. * @param {Boolean} [resetValue] If true, the method resets field value to empty or remove checked/selected attribute (for radio/checkbox)
  1361. * @returns {BootstrapValidator}
  1362. */
  1363. resetForm: function(resetValue) {
  1364. for (var field in this.options.fields) {
  1365. this.resetField(field, resetValue);
  1366. }
  1367. this.$invalidFields = $([]);
  1368. this.$submitButton = null;
  1369. // Enable submit buttons
  1370. this.disableSubmitButtons(false);
  1371. return this;
  1372. },
  1373. /**
  1374. * Revalidate given field
  1375. * It's used when you need to revalidate the field which its value is updated by other plugin
  1376. *
  1377. * @param {String|jQuery} field The field name of field element
  1378. * @returns {BootstrapValidator}
  1379. */
  1380. revalidateField: function(field) {
  1381. this.updateStatus(field, this.STATUS_NOT_VALIDATED)
  1382. .validateField(field);
  1383. return this;
  1384. },
  1385. /**
  1386. * Enable/Disable all validators to given field
  1387. *
  1388. * @param {String} field The field name
  1389. * @param {Boolean} enabled Enable/Disable field validators
  1390. * @param {String} [validatorName] The validator name. If null, all validators will be enabled/disabled
  1391. * @returns {BootstrapValidator}
  1392. */
  1393. enableFieldValidators: function(field, enabled, validatorName) {
  1394. var validators = this.options.fields[field].validators;
  1395. // Enable/disable particular validator
  1396. if (validatorName
  1397. && validators
  1398. && validators[validatorName] && validators[validatorName].enabled !== enabled)
  1399. {
  1400. this.options.fields[field].validators[validatorName].enabled = enabled;
  1401. this.updateStatus(field, this.STATUS_NOT_VALIDATED, validatorName);
  1402. }
  1403. // Enable/disable all validators
  1404. else if (!validatorName && this.options.fields[field].enabled !== enabled) {
  1405. this.options.fields[field].enabled = enabled;
  1406. for (var v in validators) {
  1407. this.enableFieldValidators(field, enabled, v);
  1408. }
  1409. }
  1410. return this;
  1411. },
  1412. /**
  1413. * Some validators have option which its value is dynamic.
  1414. * For example, the zipCode validator has the country option which might be changed dynamically by a select element.
  1415. *
  1416. * @param {jQuery|String} field The field name or element
  1417. * @param {String|Function} option The option which can be determined by:
  1418. * - a string
  1419. * - name of field which defines the value
  1420. * - name of function which returns the value
  1421. * - a function returns the value
  1422. *
  1423. * The callback function has the format of
  1424. * callback: function(value, validator, $field) {
  1425. * // value is the value of field
  1426. * // validator is the BootstrapValidator instance
  1427. * // $field is the field element
  1428. * }
  1429. *
  1430. * @returns {String}
  1431. */
  1432. getDynamicOption: function(field, option) {
  1433. var $field = ('string' === typeof field) ? this.getFieldElements(field) : field,
  1434. value = $field.val();
  1435. // Option can be determined by
  1436. // ... a function
  1437. if ('function' === typeof option) {
  1438. return $.fn.bootstrapValidator.helpers.call(option, [value, this, $field]);
  1439. }
  1440. // ... value of other field
  1441. else if ('string' === typeof option) {
  1442. var $f = this.getFieldElements(option);
  1443. if ($f.length) {
  1444. return $f.val();
  1445. }
  1446. // ... return value of callback
  1447. else {
  1448. return $.fn.bootstrapValidator.helpers.call(option, [value, this, $field]) || option;
  1449. }
  1450. }
  1451. return null;
  1452. },
  1453. /**
  1454. * Destroy the plugin
  1455. * It will remove all error messages, feedback icons and turn off the events
  1456. */
  1457. destroy: function() {
  1458. var field, fields, $field, validator, $icon, group;
  1459. for (field in this.options.fields) {
  1460. fields = this.getFieldElements(field);
  1461. group = this.options.fields[field].group || this.options.group;
  1462. for (var i = 0; i < fields.length; i++) {
  1463. $field = fields.eq(i);
  1464. $field
  1465. // Remove all error messages
  1466. .data('bv.messages')
  1467. .find('.help-block[data-bv-validator][data-bv-for="' + field + '"]').remove().end()
  1468. .end()
  1469. .removeData('bv.messages')
  1470. // Remove feedback classes
  1471. .parents(group)
  1472. .removeClass('has-feedback has-error has-success')
  1473. .end()
  1474. // Turn off events
  1475. .off('.bv')
  1476. .removeAttr('data-bv-field');
  1477. // Remove feedback icons, tooltip/popover container
  1478. $icon = $field.data('bv.icon');
  1479. if ($icon) {
  1480. var container = ('function' === typeof (this.options.fields[field].container || this.options.container)) ? (this.options.fields[field].container || this.options.container).call(this, $field, this) : (this.options.fields[field].container || this.options.container);
  1481. switch (container) {
  1482. case 'tooltip':
  1483. $icon.tooltip('destroy').remove();
  1484. break;
  1485. case 'popover':
  1486. $icon.popover('destroy').remove();
  1487. break;
  1488. default:
  1489. $icon.remove();
  1490. break;
  1491. }
  1492. }
  1493. $field.removeData('bv.icon');
  1494. for (validator in this.options.fields[field].validators) {
  1495. if ($field.data('bv.dfs.' + validator)) {
  1496. $field.data('bv.dfs.' + validator).reject();
  1497. }
  1498. $field.removeData('bv.result.' + validator)
  1499. .removeData('bv.response.' + validator)
  1500. .removeData('bv.dfs.' + validator);
  1501. // Destroy the validator
  1502. if ('function' === typeof $.fn.bootstrapValidator.validators[validator].destroy) {
  1503. $.fn.bootstrapValidator.validators[validator].destroy(this, $field, this.options.fields[field].validators[validator]);
  1504. }
  1505. }
  1506. }
  1507. }
  1508. this.disableSubmitButtons(false); // Enable submit buttons
  1509. this.$hiddenButton.remove(); // Remove the hidden button
  1510. this.$form
  1511. .removeClass(this.options.elementClass)
  1512. .off('.bv')
  1513. .removeData('bootstrapValidator')
  1514. // Remove generated hidden elements
  1515. .find('[data-bv-submit-hidden]').remove().end()
  1516. .find('[type="submit"]').off('click.bv');
  1517. }
  1518. };
  1519. // Plugin definition
  1520. $.fn.bootstrapValidator = function(option) {
  1521. var params = arguments;
  1522. return this.each(function() {
  1523. var $this = $(this),
  1524. data = $this.data('bootstrapValidator'),
  1525. options = 'object' === typeof option && option;
  1526. if (!data) {
  1527. data = new BootstrapValidator(this, options);
  1528. $this.data('bootstrapValidator', data);
  1529. }
  1530. // Allow to call plugin method
  1531. if ('string' === typeof option) {
  1532. data[option].apply(data, Array.prototype.slice.call(params, 1));
  1533. }
  1534. });
  1535. };
  1536. // The default options
  1537. // Sorted in alphabetical order
  1538. $.fn.bootstrapValidator.DEFAULT_OPTIONS = {
  1539. // The first invalid field will be focused automatically
  1540. autoFocus: true,
  1541. //The error messages container. It can be:
  1542. // - 'tooltip' if you want to use Bootstrap tooltip to show error messages
  1543. // - 'popover' if you want to use Bootstrap popover to show error messages
  1544. // - a CSS selector indicating the container
  1545. // In the first two cases, since the tooltip/popover should be small enough, the plugin only shows only one error message
  1546. // You also can define the message container for particular field
  1547. container: null,
  1548. // The form CSS class
  1549. elementClass: 'bv-form',
  1550. // Use custom event name to avoid window.onerror being invoked by jQuery
  1551. // See https://github.com/nghuuphuoc/bootstrapvalidator/issues/630
  1552. events: {
  1553. formInit: 'init.form.bv',
  1554. formError: 'error.form.bv',
  1555. formSuccess: 'success.form.bv',
  1556. fieldAdded: 'added.field.bv',
  1557. fieldRemoved: 'removed.field.bv',
  1558. fieldInit: 'init.field.bv',
  1559. fieldError: 'error.field.bv',
  1560. fieldSuccess: 'success.field.bv',
  1561. fieldStatus: 'status.field.bv',
  1562. validatorError: 'error.validator.bv',
  1563. validatorSuccess: 'success.validator.bv'
  1564. },
  1565. // Indicate fields which won't be validated
  1566. // By default, the plugin will not validate the following kind of fields:
  1567. // - disabled
  1568. // - hidden
  1569. // - invisible
  1570. //
  1571. // The setting consists of jQuery filters. Accept 3 formats:
  1572. // - A string. Use a comma to separate filter
  1573. // - An array. Each element is a filter
  1574. // - An array. Each element can be a callback function
  1575. // function($field, validator) {
  1576. // $field is jQuery object representing the field element
  1577. // validator is the BootstrapValidator instance
  1578. // return true or false;
  1579. // }
  1580. //
  1581. // The 3 following settings are equivalent:
  1582. //
  1583. // 1) ':disabled, :hidden, :not(:visible)'
  1584. // 2) [':disabled', ':hidden', ':not(:visible)']
  1585. // 3) [':disabled', ':hidden', function($field) {
  1586. // return !$field.is(':visible');
  1587. // }]
  1588. excluded: [':disabled', ':hidden', ':not(:visible)'],
  1589. // Shows ok/error/loading icons based on the field validity.
  1590. // This feature requires Bootstrap v3.1.0 or later (http://getbootstrap.com/css/#forms-control-validation).
  1591. // Since Bootstrap doesn't provide any methods to know its version, this option cannot be on/off automatically.
  1592. // In other word, to use this feature you have to upgrade your Bootstrap to v3.1.0 or later.
  1593. //
  1594. // Examples:
  1595. // - Use Glyphicons icons:
  1596. // feedbackIcons: {
  1597. // valid: 'glyphicon glyphicon-ok',
  1598. // invalid: 'glyphicon glyphicon-remove',
  1599. // validating: 'glyphicon glyphicon-refresh'
  1600. // }
  1601. // - Use FontAwesome icons:
  1602. // feedbackIcons: {
  1603. // valid: 'fa fa-check',
  1604. // invalid: 'fa fa-times',
  1605. // validating: 'fa fa-refresh'
  1606. // }
  1607. feedbackIcons: {
  1608. valid: null,
  1609. invalid: null,
  1610. validating: null
  1611. },
  1612. // Map the field name with validator rules
  1613. fields: null,
  1614. // The CSS selector for indicating the element consists the field
  1615. // By default, each field is placed inside the <div class="form-group"></div>
  1616. // You should adjust this option if your form group consists of many fields which not all of them need to be validated
  1617. group: '.form-group',
  1618. // Live validating option
  1619. // Can be one of 3 values:
  1620. // - enabled: The plugin validates fields as soon as they are changed
  1621. // - disabled: Disable the live validating. The error messages are only shown after the form is submitted
  1622. // - submitted: The live validating is enabled after the form is submitted
  1623. live: 'enabled',
  1624. // Default invalid message
  1625. message: 'This value is not valid',
  1626. // The submit buttons selector
  1627. // These buttons will be disabled to prevent the valid form from multiple submissions
  1628. submitButtons: '[type="submit"]',
  1629. // The field will not be live validated if its length is less than this number of characters
  1630. threshold: null,
  1631. // Whether to be verbose when validating a field or not.
  1632. // Possible values:
  1633. // - true: when a field has multiple validators, all of them will be checked, and respectively - if errors occur in
  1634. // multiple validators, all of them will be displayed to the user
  1635. // - false: when a field has multiple validators, validation for this field will be terminated upon the first encountered error.
  1636. // Thus, only the very first error message related to this field will be displayed to the user
  1637. verbose: true
  1638. };
  1639. // Available validators
  1640. $.fn.bootstrapValidator.validators = {};
  1641. // i18n
  1642. $.fn.bootstrapValidator.i18n = {};
  1643. $.fn.bootstrapValidator.Constructor = BootstrapValidator;
  1644. // Helper methods, which can be used in validator class
  1645. $.fn.bootstrapValidator.helpers = {
  1646. /**
  1647. * Execute a callback function
  1648. *
  1649. * @param {String|Function} functionName Can be
  1650. * - name of global function
  1651. * - name of namespace function (such as A.B.C)
  1652. * - a function
  1653. * @param {Array} args The callback arguments
  1654. */
  1655. call: function(functionName, args) {
  1656. if ('function' === typeof functionName) {
  1657. return functionName.apply(this, args);
  1658. } else if ('string' === typeof functionName) {
  1659. if ('()' === functionName.substring(functionName.length - 2)) {
  1660. functionName = functionName.substring(0, functionName.length - 2);
  1661. }
  1662. var ns = functionName.split('.'),
  1663. func = ns.pop(),
  1664. context = window;
  1665. for (var i = 0; i < ns.length; i++) {
  1666. context = context[ns[i]];
  1667. }
  1668. return (typeof context[func] === 'undefined') ? null : context[func].apply(this, args);
  1669. }
  1670. },
  1671. /**
  1672. * Format a string
  1673. * It's used to format the error message
  1674. * format('The field must between %s and %s', [10, 20]) = 'The field must between 10 and 20'
  1675. *
  1676. * @param {String} message
  1677. * @param {Array} parameters
  1678. * @returns {String}
  1679. */
  1680. format: function(message, parameters) {
  1681. if (!$.isArray(parameters)) {
  1682. parameters = [parameters];
  1683. }
  1684. for (var i in parameters) {
  1685. message = message.replace('%s', parameters[i]);
  1686. }
  1687. return message;
  1688. },
  1689. /**
  1690. * Validate a date
  1691. *
  1692. * @param {Number} year The full year in 4 digits
  1693. * @param {Number} month The month number
  1694. * @param {Number} day The day number
  1695. * @param {Boolean} [notInFuture] If true, the date must not be in the future
  1696. * @returns {Boolean}
  1697. */
  1698. date: function(year, month, day, notInFuture) {
  1699. if (isNaN(year) || isNaN(month) || isNaN(day)) {
  1700. return false;
  1701. }
  1702. if (day.length > 2 || month.length > 2 || year.length > 4) {
  1703. return false;
  1704. }
  1705. day = parseInt(day, 10);
  1706. month = parseInt(month, 10);
  1707. year = parseInt(year, 10);
  1708. if (year < 1000 || year > 9999 || month <= 0 || month > 12) {
  1709. return false;
  1710. }
  1711. var numDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  1712. // Update the number of days in Feb of leap year
  1713. if (year % 400 === 0 || (year % 100 !== 0 && year % 4 === 0)) {
  1714. numDays[1] = 29;
  1715. }
  1716. // Check the day
  1717. if (day <= 0 || day > numDays[month - 1]) {
  1718. return false;
  1719. }
  1720. if (notInFuture === true) {
  1721. var currentDate = new Date(),
  1722. currentYear = currentDate.getFullYear(),
  1723. currentMonth = currentDate.getMonth(),
  1724. currentDay = currentDate.getDate();
  1725. return (year < currentYear
  1726. || (year === currentYear && month - 1 < currentMonth)
  1727. || (year === currentYear && month - 1 === currentMonth && day < currentDay));
  1728. }
  1729. return true;
  1730. },
  1731. /**
  1732. * Implement Luhn validation algorithm
  1733. * Credit to https://gist.github.com/ShirtlessKirk/2134376
  1734. *
  1735. * @see http://en.wikipedia.org/wiki/Luhn
  1736. * @param {String} value
  1737. * @returns {Boolean}
  1738. */
  1739. luhn: function(value) {
  1740. var length = value.length,
  1741. mul = 0,
  1742. prodArr = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]],
  1743. sum = 0;
  1744. while (length--) {
  1745. sum += prodArr[mul][parseInt(value.charAt(length), 10)];
  1746. mul ^= 1;
  1747. }
  1748. return (sum % 10 === 0 && sum > 0);
  1749. },
  1750. /**
  1751. * Implement modulus 11, 10 (ISO 7064) algorithm
  1752. *
  1753. * @param {String} value
  1754. * @returns {Boolean}
  1755. */
  1756. mod11And10: function(value) {
  1757. var check = 5,
  1758. length = value.length;
  1759. for (var i = 0; i < length; i++) {
  1760. check = (((check || 10) * 2) % 11 + parseInt(value.charAt(i), 10)) % 10;
  1761. }
  1762. return (check === 1);
  1763. },
  1764. /**
  1765. * Implements Mod 37, 36 (ISO 7064) algorithm
  1766. * Usages:
  1767. * mod37And36('A12425GABC1234002M')
  1768. * mod37And36('002006673085', '0123456789')
  1769. *
  1770. * @param {String} value
  1771. * @param {String} [alphabet]
  1772. * @returns {Boolean}
  1773. */
  1774. mod37And36: function(value, alphabet) {
  1775. alphabet = alphabet || '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  1776. var modulus = alphabet.length,
  1777. length = value.length,
  1778. check = Math.floor(modulus / 2);
  1779. for (var i = 0; i < length; i++) {
  1780. check = (((check || modulus) * 2) % (modulus + 1) + alphabet.indexOf(value.charAt(i))) % modulus;
  1781. }
  1782. return (check === 1);
  1783. }
  1784. };
  1785. }(window.jQuery));