bootstrapValidator.js 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754
  1. /**
  2. * BootstrapValidator (https://github.com/nghuuphuoc/bootstrapvalidator)
  3. *
  4. * A jQuery plugin to validate form fields. Use with Bootstrap 3
  5. *
  6. * @version v0.4.0-dev
  7. * @author https://twitter.com/nghuuphuoc
  8. * @copyright (c) 2013 - 2014 Nguyen Huu Phuoc
  9. * @license MIT
  10. */
  11. (function($) {
  12. var BootstrapValidator = function(form, options) {
  13. this.$form = $(form);
  14. this.options = $.extend({}, BootstrapValidator.DEFAULT_OPTIONS, options);
  15. this.dfds = {}; // Array of deferred
  16. this.results = {}; // Validating results
  17. this.invalidField = null; // First invalid field
  18. this.$submitButton = null; // The submit button which is clicked to submit form
  19. this._init();
  20. this.STATUS_NOT_VALIDATED = 'NOT_VALIDATED';
  21. this.STATUS_VALIDATING = 'VALIDATING';
  22. this.STATUS_INVALID = 'INVALID';
  23. this.STATUS_VALID = 'VALID';
  24. };
  25. // The default options
  26. BootstrapValidator.DEFAULT_OPTIONS = {
  27. // The form CSS class
  28. elementClass: 'bootstrap-validator-form',
  29. // Default invalid message
  30. message: 'This value is not valid',
  31. // Shows ok/error/loading icons based on the field validity.
  32. // This feature requires Bootstrap v3.1.0 or later (http://getbootstrap.com/css/#forms-control-validation).
  33. // Since Bootstrap doesn't provide any methods to know its version, this option cannot be on/off automatically.
  34. // In other word, to use this feature you have to upgrade your Bootstrap to v3.1.0 or later.
  35. //
  36. // Examples:
  37. // - Use Glyphicons icons:
  38. // feedbackIcons: {
  39. // valid: 'glyphicon glyphicon-ok',
  40. // invalid: 'glyphicon glyphicon-remove',
  41. // validating: 'glyphicon glyphicon-refresh'
  42. // }
  43. // - Use FontAwesome icons:
  44. // feedbackIcons: {
  45. // valid: 'fa fa-check',
  46. // invalid: 'fa fa-times',
  47. // validating: 'fa fa-refresh'
  48. // }
  49. feedbackIcons: {
  50. valid: null,
  51. invalid: null,
  52. validating: null
  53. },
  54. // The submit buttons selector
  55. // These buttons will be disabled to prevent the valid form from multiple submissions
  56. submitButtons: 'button[type="submit"]',
  57. // The custom submit handler
  58. // It will prevent the form from the default submission
  59. //
  60. // submitHandler: function(validator, form) {
  61. // - validator is the BootstrapValidator instance
  62. // - form is the jQuery object present the current form
  63. // }
  64. submitHandler: null,
  65. // Live validating option
  66. // Can be one of 3 values:
  67. // - enabled: The plugin validates fields as soon as they are changed
  68. // - disabled: Disable the live validating. The error messages are only shown after the form is submitted
  69. // - submitted: The live validating is enabled after the form is submitted
  70. live: 'enabled',
  71. // Map the field name with validator rules
  72. fields: null
  73. };
  74. BootstrapValidator.prototype = {
  75. constructor: BootstrapValidator,
  76. /**
  77. * Init form
  78. */
  79. _init: function() {
  80. var that = this,
  81. options = {
  82. trigger: this.$form.attr('data-bv-trigger'),
  83. message: this.$form.attr('data-bv-message'),
  84. submitButtons: this.$form.attr('data-bv-submitbuttons'),
  85. live: this.$form.attr('data-bv-live'),
  86. fields: {},
  87. feedbackIcons: {
  88. valid: this.$form.attr('data-bv-feedbackicons-valid'),
  89. invalid: this.$form.attr('data-bv-feedbackicons-invalid'),
  90. validating: this.$form.attr('data-bv-feedbackicons-validating')
  91. }
  92. },
  93. validator,
  94. i = 0,
  95. v, // Validator name
  96. enabled,
  97. optionName,
  98. optionValue,
  99. html5Attrs;
  100. this.$form
  101. // Disable client side validation in HTML 5
  102. .attr('novalidate', 'novalidate')
  103. .addClass(this.options.elementClass)
  104. // Disable the default submission first
  105. .on('submit.bootstrapValidator', function(e) {
  106. e.preventDefault();
  107. that.validate();
  108. })
  109. .on('click', this.options.submitButtons, function() {
  110. that.$submitButton = $(this);
  111. })
  112. // Find all fields which have either "name" or "data-bv-field" attribute
  113. .find('[name], [data-bv-field]').each(function() {
  114. var $field = $(this),
  115. field = $field.attr('name') || $field.attr('data-bv-field');
  116. $field.attr('data-bv-field', field);
  117. options.fields[field] = $.extend({}, {
  118. trigger: $field.attr('data-bv-trigger'),
  119. message: $field.attr('data-bv-message'),
  120. container: $field.attr('data-bv-container'),
  121. selector: $field.attr('data-bv-selector'),
  122. validators: {}
  123. }, options.fields[field]);
  124. for (v in $.fn.bootstrapValidator.validators) {
  125. validator = $.fn.bootstrapValidator.validators[v];
  126. enabled = $field.attr('data-bv-' + v.toLowerCase()) + '';
  127. html5Attrs = {};
  128. if (('function' == typeof validator.enableByHtml5
  129. && (html5Attrs = validator.enableByHtml5($(this)))
  130. && (enabled != 'false'))
  131. || ('undefined' == typeof validator.enableByHtml5 && ('' == enabled || 'true' == enabled)))
  132. {
  133. // Try to parse the options via attributes
  134. validator.html5Attributes = validator.html5Attributes || ['message'];
  135. options.fields[field]['validators'][v] = $.extend({}, html5Attrs == true ? {} : html5Attrs, options.fields[field]['validators'][v]);
  136. for (i in validator.html5Attributes) {
  137. optionName = validator.html5Attributes[i];
  138. optionValue = $field.attr('data-bv-' + v.toLowerCase() + '-' + optionName.toLowerCase());
  139. if (optionValue) {
  140. if ('true' == optionValue) {
  141. optionValue = true;
  142. } else if ('false' == optionValue) {
  143. optionValue = false;
  144. }
  145. options.fields[field]['validators'][v][optionName] = optionValue;
  146. }
  147. }
  148. }
  149. }
  150. });
  151. this.options = $.extend(true, this.options, options);
  152. //console.log(this.options);
  153. for (var field in this.options.fields) {
  154. this._initField(field);
  155. }
  156. this._setLiveValidating();
  157. },
  158. /**
  159. * Init field
  160. *
  161. * @param {String} field The field name
  162. */
  163. _initField: function(field) {
  164. if (this.options.fields[field] == null || this.options.fields[field].validators == null) {
  165. return;
  166. }
  167. this.dfds[field] = {};
  168. this.results[field] = {};
  169. var fields = this.getFieldElements(field);
  170. // We don't need to validate non-existing fields
  171. if (fields == null) {
  172. delete this.options.fields[field];
  173. delete this.dfds[field];
  174. return;
  175. }
  176. fields.attr('data-bv-field', field);
  177. // Create help block elements for showing the error messages
  178. var $field = $(fields[0]),
  179. $parent = $field.parents('.form-group'),
  180. // Allow user to indicate where the error messages are shown
  181. $message = this.options.fields[field].container ? $parent.find(this.options.fields[field].container) : this._getMessageContainer($field);
  182. $field.data('bootstrapValidator.messageContainer', $message);
  183. for (var validatorName in this.options.fields[field].validators) {
  184. if (!$.fn.bootstrapValidator.validators[validatorName]) {
  185. delete this.options.fields[field].validators[validatorName];
  186. continue;
  187. }
  188. this.results[field][validatorName] = this.STATUS_NOT_VALIDATED;
  189. $('<small/>')
  190. .css('display', 'none')
  191. .attr('data-bv-validator', validatorName)
  192. .html(this.options.fields[field].validators[validatorName].message || this.options.fields[field].message || this.options.message)
  193. .addClass('help-block')
  194. .appendTo($message);
  195. }
  196. // Prepare the feedback icons
  197. // Available from Bootstrap 3.1 (http://getbootstrap.com/css/#forms-control-validation)
  198. if (this.options.feedbackIcons
  199. && this.options.feedbackIcons.validating && this.options.feedbackIcons.invalid && this.options.feedbackIcons.valid)
  200. {
  201. $parent.addClass('has-feedback');
  202. var $icon = $('<i/>').css('display', 'none').addClass('form-control-feedback').attr('data-bv-field', field).insertAfter($(fields[fields.length - 1]));
  203. // The feedback icon does not render correctly if there is no label
  204. // https://github.com/twbs/bootstrap/issues/12873
  205. if ($parent.find('label').length == 0) {
  206. $icon.css('top', 0);
  207. }
  208. }
  209. if (this.options.fields[field]['enabled'] == null) {
  210. this.options.fields[field]['enabled'] = true;
  211. }
  212. // Whenever the user change the field value, mark it as not validated yet
  213. var that = this,
  214. type = fields.attr('type'),
  215. event = ('radio' == type || 'checkbox' == type || 'file' == type || 'SELECT' == fields[0].tagName) ? 'change' : 'keyup';
  216. fields.on(event + '.bootstrapValidator', function() {
  217. that.updateStatus($field, that.STATUS_NOT_VALIDATED, null);
  218. });
  219. },
  220. /**
  221. * Get the element to place the error messages
  222. *
  223. * @param {jQuery} $field The field element
  224. * @returns {jQuery}
  225. */
  226. _getMessageContainer: function($field) {
  227. var $parent = $field.parent();
  228. if ($parent.hasClass('form-group')) {
  229. return $parent;
  230. }
  231. var cssClasses = $parent.attr('class');
  232. if (!cssClasses) {
  233. return this._getMessageContainer($parent);
  234. }
  235. cssClasses = cssClasses.split(' ');
  236. var n = cssClasses.length;
  237. for (var i = 0; i < n; i++) {
  238. if (/^col-(xs|sm|md|lg)-\d+$/.test(cssClasses[i]) || /^col-(xs|sm|md|lg)-offset-\d+$/.test(cssClasses[i])) {
  239. return $parent;
  240. }
  241. }
  242. return this._getMessageContainer($parent);
  243. },
  244. /**
  245. * Enable live validating
  246. */
  247. _setLiveValidating: function() {
  248. if ('enabled' == this.options.live) {
  249. var that = this;
  250. for (var field in this.options.fields) {
  251. (function(f) {
  252. var fields = that.getFieldElements(f);
  253. if (fields) {
  254. var type = fields.attr('type'),
  255. trigger = that.options.fields[field].trigger
  256. || that.options.trigger
  257. || (('radio' == type || 'checkbox' == type || 'file' == type || 'SELECT' == fields[0].tagName) ? 'change' : 'keyup'),
  258. events = trigger.split(' ').map(function(item) {
  259. return item + '.bootstrapValidator';
  260. }).join(' ');
  261. fields.on(events, function() {
  262. that.validateField(f);
  263. });
  264. }
  265. })(field);
  266. }
  267. }
  268. },
  269. /**
  270. * Disable/Enable submit buttons
  271. *
  272. * @param {Boolean} disabled
  273. */
  274. _disableSubmitButtons: function(disabled) {
  275. if (!disabled) {
  276. this.$form.find(this.options.submitButtons).removeAttr('disabled');
  277. } else if (this.options.live != 'disabled') {
  278. // Don't disable if the live validating mode is disabled
  279. this.$form.find(this.options.submitButtons).attr('disabled', 'disabled');
  280. }
  281. },
  282. /**
  283. * Called when all validations are completed
  284. */
  285. _submit: function() {
  286. if (!this.isValid()) {
  287. if ('submitted' == this.options.live) {
  288. this.options.live = 'enabled';
  289. this._setLiveValidating();
  290. }
  291. // Focus to the first invalid field
  292. if (this.invalidField) {
  293. this.getFieldElements(this.invalidField).focus();
  294. }
  295. return;
  296. }
  297. this._disableSubmitButtons(true);
  298. // Call the custom submission if enabled
  299. if (this.options.submitHandler && 'function' == typeof this.options.submitHandler) {
  300. // Turn off the submit handler, so user can call form.submit() inside their submitHandler method
  301. this.$form.off('submit.bootstrapValidator');
  302. this.options.submitHandler.call(this, this, this.$form, this.$submitButton);
  303. } else {
  304. // Submit form
  305. this.$form.off('submit.bootstrapValidator').submit();
  306. }
  307. },
  308. // --- Public methods ---
  309. /**
  310. * Retrieve the field elements by given name
  311. *
  312. * @param {String} field The field name
  313. * @returns {null|jQuery[]}
  314. */
  315. getFieldElements: function(field) {
  316. var fields = this.$form.find(this.options.fields[field].selector || '[name="' + field + '"]');
  317. return (fields.length == 0) ? null : fields;
  318. },
  319. /**
  320. * Validate the form
  321. *
  322. * @return {BootstrapValidator}
  323. */
  324. validate: function() {
  325. if (!this.options.fields) {
  326. return this;
  327. }
  328. this._disableSubmitButtons(true);
  329. for (var field in this.options.fields) {
  330. this.validateField(field);
  331. }
  332. this._submit();
  333. return this;
  334. },
  335. /**
  336. * Validate given field
  337. *
  338. * @param {String} field The field name
  339. */
  340. validateField: function(field) {
  341. if (!this.options.fields[field]['enabled']) {
  342. return;
  343. }
  344. var that = this,
  345. fields = this.getFieldElements(field),
  346. $field = $(fields[0]),
  347. validators = this.options.fields[field].validators,
  348. validatorName,
  349. validateResult;
  350. // We don't need to validate disabled field
  351. if (fields.length == 1 && fields.is(':disabled')) {
  352. delete this.options.fields[field];
  353. delete this.dfds[field];
  354. return;
  355. }
  356. for (validatorName in validators) {
  357. if (this.dfds[field][validatorName]) {
  358. this.dfds[field][validatorName].reject();
  359. }
  360. // Don't validate field if it is already done
  361. if (this.results[field][validatorName] == this.STATUS_VALID || this.results[field][validatorName] == this.STATUS_INVALID) {
  362. continue;
  363. }
  364. this.results[field][validatorName] = this.STATUS_VALIDATING;
  365. validateResult = $.fn.bootstrapValidator.validators[validatorName].validate(this, $field, validators[validatorName]);
  366. if ('object' == typeof validateResult) {
  367. this.updateStatus($field, this.STATUS_VALIDATING, validatorName);
  368. this.dfds[field][validatorName] = validateResult;
  369. validateResult.done(function(isValid, v) {
  370. // v is validator name
  371. delete that.dfds[field][v];
  372. that.updateStatus($field, isValid ? that.STATUS_VALID : that.STATUS_INVALID, v);
  373. if (isValid && 'disabled' == that.options.live) {
  374. that._submit();
  375. }
  376. });
  377. } else if ('boolean' == typeof validateResult) {
  378. this.updateStatus($field, validateResult ? this.STATUS_VALID : this.STATUS_INVALID, validatorName);
  379. }
  380. }
  381. },
  382. /**
  383. * Check the form validity
  384. *
  385. * @returns {Boolean}
  386. */
  387. isValid: function() {
  388. var field, validatorName;
  389. for (field in this.results) {
  390. if (this.options.fields[field] == null || !this.options.fields[field]['enabled']) {
  391. continue;
  392. }
  393. for (validatorName in this.results[field]) {
  394. if (this.results[field][validatorName] == this.STATUS_NOT_VALIDATED || this.results[field][validatorName] == this.STATUS_VALIDATING) {
  395. return false;
  396. }
  397. if (this.results[field][validatorName] == this.STATUS_INVALID) {
  398. this.invalidField = field;
  399. return false;
  400. }
  401. }
  402. }
  403. return true;
  404. },
  405. /**
  406. * Update field status
  407. *
  408. * @param {String|jQuery} field The field name or field element
  409. * @param {String} status The status
  410. * Can be 'NOT_VALIDATED', 'VALIDATING', 'INVALID' or 'VALID'
  411. * @param {String|null} validatorName The validator name. If null, the method updates validity result for all validators
  412. * @return {BootstrapValidator}
  413. */
  414. updateStatus: function(field, status, validatorName) {
  415. var $field = ('string' == typeof field) ? this.getFieldElements(field) : field,
  416. that = this,
  417. field = $field.attr('data-bv-field'),
  418. $parent = $field.parents('.form-group'),
  419. $message = $field.data('bootstrapValidator.messageContainer'),
  420. $errors = $message.find('.help-block[data-bv-validator]'),
  421. $icon = $parent.find('.form-control-feedback[data-bv-field="' + field + '"]');
  422. // Update status
  423. if (validatorName) {
  424. this.results[field][validatorName] = status;
  425. } else {
  426. for (var v in this.options.fields[field].validators) {
  427. this.results[field][v] = status;
  428. }
  429. }
  430. // Show/hide error elements and feedback icons
  431. switch (status) {
  432. case this.STATUS_VALIDATING:
  433. this._disableSubmitButtons(true);
  434. $parent.removeClass('has-success').removeClass('has-error');
  435. // TODO: Show validating message
  436. validatorName ? $errors.filter('.help-block[data-bv-validator="' + validatorName + '"]').hide() : $errors.hide();
  437. if ($icon) {
  438. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).addClass(this.options.feedbackIcons.validating).show();
  439. }
  440. break;
  441. case this.STATUS_INVALID:
  442. this._disableSubmitButtons(true);
  443. $parent.removeClass('has-success').addClass('has-error');
  444. validatorName ? $errors.filter('[data-bv-validator="' + validatorName + '"]').show() : $errors.show();
  445. if ($icon) {
  446. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.validating).addClass(this.options.feedbackIcons.invalid).show();
  447. }
  448. break;
  449. case this.STATUS_VALID:
  450. validatorName ? $errors.filter('[data-bv-validator="' + validatorName + '"]').hide() : $errors.hide();
  451. // If the field is valid
  452. if ($errors.filter(function() {
  453. var display = $(this).css('display'), v = $(this).attr('data-bv-validator');
  454. return ('block' == display) || (that.results[field][v] != that.STATUS_VALID);
  455. }).length == 0
  456. ) {
  457. this._disableSubmitButtons(false);
  458. $parent.removeClass('has-error').addClass('has-success');
  459. if ($icon) {
  460. $icon.removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).addClass(this.options.feedbackIcons.valid).show();
  461. }
  462. }
  463. break;
  464. case this.STATUS_NOT_VALIDATED:
  465. default:
  466. this._disableSubmitButtons(false);
  467. $parent.removeClass('has-success').removeClass('has-error');
  468. validatorName ? $errors.filter('.help-block[data-bv-validator="' + validatorName + '"]').hide() : $errors.hide();
  469. if ($icon) {
  470. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).hide();
  471. }
  472. break;
  473. }
  474. return this;
  475. },
  476. // Useful APIs which aren't used internally
  477. /**
  478. * Reset the form
  479. *
  480. * @param {Boolean} resetFormData Reset current form data
  481. * @return {BootstrapValidator}
  482. */
  483. resetForm: function(resetFormData) {
  484. var field, $field, type;
  485. for (field in this.options.fields) {
  486. this.dfds[field] = {};
  487. this.results[field] = {};
  488. $field = this.getFieldElements(field);
  489. // Mark field as not validated yet
  490. this.updateStatus($field, this.STATUS_NOT_VALIDATED, null);
  491. if (resetFormData) {
  492. type = $field.attr('type');
  493. ('radio' == type || 'checkbox' == type) ? $field.removeAttr('checked').removeAttr('selected') : $field.val('');
  494. }
  495. }
  496. this.invalidField = null;
  497. this.$submitButton = null;
  498. // Enable submit buttons
  499. this._disableSubmitButtons(false);
  500. return this;
  501. },
  502. /**
  503. * Enable/Disable all validators to given field
  504. *
  505. * @param {String} field The field name
  506. * @param {Boolean} enabled Enable/Disable field validators
  507. * @return {BootstrapValidator}
  508. */
  509. enableFieldValidators: function(field, enabled) {
  510. this.options.fields[field]['enabled'] = enabled;
  511. this.updateStatus(field, this.STATUS_NOT_VALIDATED, null);
  512. return this;
  513. }
  514. };
  515. // Plugin definition
  516. $.fn.bootstrapValidator = function(options) {
  517. return this.each(function() {
  518. var $this = $(this), data = $this.data('bootstrapValidator');
  519. if (!data) {
  520. $this.data('bootstrapValidator', (data = new BootstrapValidator(this, options)));
  521. }
  522. if ('string' == typeof options) {
  523. data[options]();
  524. }
  525. });
  526. };
  527. // Available validators
  528. $.fn.bootstrapValidator.validators = {};
  529. $.fn.bootstrapValidator.Constructor = BootstrapValidator;
  530. }(window.jQuery));
  531. ;(function($) {
  532. $.fn.bootstrapValidator.validators.base64 = {
  533. /**
  534. * Return true if the input value is a base 64 encoded string.
  535. *
  536. * @param {BootstrapValidator} validator The validator plugin instance
  537. * @param {jQuery} $field Field element
  538. * @param {Object} options Can consist of the following keys:
  539. * - message: The invalid message
  540. * @returns {Boolean}
  541. */
  542. validate: function(validator, $field, options) {
  543. var value = $field.val();
  544. if (value == '') {
  545. return true;
  546. }
  547. return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/.test(value);
  548. }
  549. };
  550. }(window.jQuery));
  551. ;(function($) {
  552. $.fn.bootstrapValidator.validators.between = {
  553. /**
  554. * Return true if the input value is between (strictly or not) two given numbers
  555. *
  556. * @param {BootstrapValidator} validator The validator plugin instance
  557. * @param {jQuery} $field Field element
  558. * @param {Object} options Can consist of the following keys:
  559. * - min
  560. * - max
  561. * - inclusive [optional]: Can be true or false. Default is true
  562. * - message: The invalid message
  563. * @returns {Boolean}
  564. */
  565. validate: function(validator, $field, options) {
  566. var value = $field.val();
  567. if (value == '') {
  568. return true;
  569. }
  570. value = parseFloat(value);
  571. return (options.inclusive === true)
  572. ? (value > options.min && value < options.max)
  573. : (value >= options.min && value <= options.max);
  574. }
  575. };
  576. }(window.jQuery));
  577. ;(function($) {
  578. $.fn.bootstrapValidator.validators.callback = {
  579. /**
  580. * Return result from the callback method
  581. *
  582. * @param {BootstrapValidator} validator The validator plugin instance
  583. * @param {jQuery} $field Field element
  584. * @param {Object} options Can consist of the following keys:
  585. * - callback: The callback method that passes 2 parameters:
  586. * callback: function(fieldValue, validator) {
  587. * // fieldValue is the value of field
  588. * // validator is instance of BootstrapValidator
  589. * }
  590. * - message: The invalid message
  591. * @returns {Boolean|Deferred}
  592. */
  593. validate: function(validator, $field, options) {
  594. var value = $field.val();
  595. if (options.callback && 'function' == typeof options.callback) {
  596. var dfd = new $.Deferred();
  597. dfd.resolve(options.callback.call(this, value, validator), 'callback');
  598. return dfd;
  599. }
  600. return true;
  601. }
  602. };
  603. }(window.jQuery));
  604. ;(function($) {
  605. $.fn.bootstrapValidator.validators.choice = {
  606. html5Attributes: ['message', 'min', 'max'],
  607. /**
  608. * Check if the number of checked boxes are less or more than a given number
  609. *
  610. * @param {BootstrapValidator} validator The validator plugin instance
  611. * @param {jQuery} $field Field element
  612. * @param {Object} options Consists of following keys:
  613. * - min
  614. * - max
  615. * At least one of two keys is required
  616. * @returns {Boolean}
  617. */
  618. validate: function(validator, $field, options) {
  619. var numChoices = validator
  620. .getFieldElements($field.attr('data-bv-field'))
  621. .filter(':checked')
  622. .length;
  623. if ((options.min && numChoices < options.min) || (options.max && numChoices > options.max)) {
  624. return false;
  625. }
  626. return true;
  627. }
  628. };
  629. }(window.jQuery));
  630. ;(function($) {
  631. $.fn.bootstrapValidator.validators.creditCard = {
  632. /**
  633. * Return true if the input value is valid credit card number
  634. * Based on https://gist.github.com/DiegoSalazar/4075533
  635. *
  636. * @param {BootstrapValidator} validator The validator plugin instance
  637. * @param {jQuery} $field Field element
  638. * @param {Object} options Can consist of the following key:
  639. * - message: The invalid message
  640. * @returns {Boolean}
  641. */
  642. validate: function(validator, $field, options) {
  643. var value = $field.val();
  644. if (value == '') {
  645. return true;
  646. }
  647. // Accept only digits, dashes or spaces
  648. if (/[^0-9-\s]+/.test(value)) {
  649. return false;
  650. }
  651. value = value.replace(/\D/g, '');
  652. // Validate the check sum
  653. // The Luhn Algorithm
  654. // http://en.wikipedia.org/wiki/Luhn
  655. var check = 0, digit = 0, even = false, length = value.length;
  656. for (var n = length - 1; n >= 0; n--) {
  657. digit = parseInt(value.charAt(n), 10);
  658. if (even) {
  659. if ((digit *= 2) > 9) {
  660. digit -= 9;
  661. }
  662. }
  663. check += digit;
  664. even = !even;
  665. }
  666. if ((check % 10) != 0) {
  667. return false;
  668. }
  669. // Validate the card number based on prefix (IIN ranges) and length
  670. var cards = {
  671. AMERICAN_EXPRESS: {
  672. length: [15],
  673. prefix: ['34', '37']
  674. },
  675. DINERS_CLUB: {
  676. length: [14],
  677. prefix: ['300', '301', '302', '303', '304', '305', '36']
  678. },
  679. DINERS_CLUB_US: {
  680. length: [16],
  681. prefix: ['54', '55']
  682. },
  683. DISCOVER: {
  684. length: [16],
  685. prefix: ['6011', '622126', '622127', '622128', '622129', '62213',
  686. '62214', '62215', '62216', '62217', '62218', '62219',
  687. '6222', '6223', '6224', '6225', '6226', '6227', '6228',
  688. '62290', '62291', '622920', '622921', '622922', '622923',
  689. '622924', '622925', '644', '645', '646', '647', '648',
  690. '649', '65']
  691. },
  692. JCB: {
  693. length: [16],
  694. prefix: ['3528', '3529', '353', '354', '355', '356', '357', '358']
  695. },
  696. LASER: {
  697. length: [16, 17, 18, 19],
  698. prefix: ['3528', '3529', '353', '354', '355', '356', '357', '358']
  699. },
  700. MAESTRO: {
  701. length: [12, 13, 14, 15, 16, 17, 18, 19],
  702. prefix: ['5018', '5020', '5038', '6304', '6759', '6761', '6762', '6763', '6764', '6765', '6766']
  703. },
  704. MASTERCARD: {
  705. length: [16],
  706. prefix: ['51', '52', '53', '54', '55']
  707. },
  708. SOLO: {
  709. length: [16, 18, 19],
  710. prefix: ['6334', '6767']
  711. },
  712. UNIONPAY: {
  713. length: [16, 17, 18, 19],
  714. prefix: ['622126', '622127', '622128', '622129', '62213', '62214',
  715. '62215', '62216', '62217', '62218', '62219', '6222', '6223',
  716. '6224', '6225', '6226', '6227', '6228', '62290', '62291',
  717. '622920', '622921', '622922', '622923', '622924', '622925']
  718. },
  719. VISA: {
  720. length: [16],
  721. prefix: ['4']
  722. }
  723. };
  724. var type, i;
  725. for (type in cards) {
  726. for (i in cards[type]['prefix']) {
  727. if (value.substr(0, cards[type]['prefix'][i].length) == cards[type]['prefix'][i] // Check the prefix
  728. && cards[type]['length'].indexOf(value.length) != -1) // and length
  729. {
  730. return true;
  731. }
  732. }
  733. }
  734. return false;
  735. }
  736. };
  737. }(window.jQuery));
  738. ;(function($) {
  739. $.fn.bootstrapValidator.validators.cvv = {
  740. /**
  741. * Return true if the input value is a valid CVV number.
  742. *
  743. * @param {BootstrapValidator} validator The validator plugin instance
  744. * @param {jQuery} $field Field element
  745. * @param {Object} options Can consist of the following keys:
  746. * - creditCardField: The credit card number field. It can be null
  747. * - message: The invalid message
  748. * @returns {Boolean}
  749. */
  750. validate: function(validator, $field, options) {
  751. var value = $field.val();
  752. if (value == '') {
  753. return true;
  754. }
  755. if (!/^[0-9]{3,4}$/.test(value)) {
  756. return false;
  757. }
  758. if (!options.creditCardField) {
  759. return true;
  760. }
  761. // Get the credit card number
  762. var creditCard = validator.getFieldElements(options.creditCardField).val();
  763. if (creditCard == '') {
  764. return true;
  765. }
  766. // Supported credit card types
  767. var cards = {
  768. AMERICAN_EXPRESS: {
  769. length: [15],
  770. prefix: ['34', '37']
  771. },
  772. DINERS_CLUB: {
  773. length: [14],
  774. prefix: ['300', '301', '302', '303', '304', '305', '36']
  775. },
  776. DINERS_CLUB_US: {
  777. length: [16],
  778. prefix: ['54', '55']
  779. },
  780. DISCOVER: {
  781. length: [16],
  782. prefix: ['6011', '622126', '622127', '622128', '622129', '62213',
  783. '62214', '62215', '62216', '62217', '62218', '62219',
  784. '6222', '6223', '6224', '6225', '6226', '6227', '6228',
  785. '62290', '62291', '622920', '622921', '622922', '622923',
  786. '622924', '622925', '644', '645', '646', '647', '648',
  787. '649', '65']
  788. },
  789. JCB: {
  790. length: [16],
  791. prefix: ['3528', '3529', '353', '354', '355', '356', '357', '358']
  792. },
  793. LASER: {
  794. length: [16, 17, 18, 19],
  795. prefix: ['3528', '3529', '353', '354', '355', '356', '357', '358']
  796. },
  797. MAESTRO: {
  798. length: [12, 13, 14, 15, 16, 17, 18, 19],
  799. prefix: ['5018', '5020', '5038', '6304', '6759', '6761', '6762', '6763', '6764', '6765', '6766']
  800. },
  801. MASTERCARD: {
  802. length: [16],
  803. prefix: ['51', '52', '53', '54', '55']
  804. },
  805. SOLO: {
  806. length: [16, 18, 19],
  807. prefix: ['6334', '6767']
  808. },
  809. UNIONPAY: {
  810. length: [16, 17, 18, 19],
  811. prefix: ['622126', '622127', '622128', '622129', '62213', '62214',
  812. '62215', '62216', '62217', '62218', '62219', '6222', '6223',
  813. '6224', '6225', '6226', '6227', '6228', '62290', '62291',
  814. '622920', '622921', '622922', '622923', '622924', '622925']
  815. },
  816. VISA: {
  817. length: [16],
  818. prefix: ['4']
  819. }
  820. };
  821. var type, i, creditCardType = null;
  822. for (type in cards) {
  823. for (i in cards[type]['prefix']) {
  824. if (creditCard.substr(0, cards[type]['prefix'][i].length) == cards[type]['prefix'][i] // Check the prefix
  825. && cards[type]['length'].indexOf(creditCard.length) != -1) // and length
  826. {
  827. creditCardType = type;
  828. break;
  829. }
  830. }
  831. }
  832. return (creditCardType == null)
  833. ? false
  834. : (('AMERICAN_EXPRESS' == creditCardType) ? (value.length == 4) : (value.length == 3));
  835. }
  836. };
  837. }(window.jQuery));
  838. ;(function($) {
  839. $.fn.bootstrapValidator.validators.date = {
  840. html5Attributes: ['message', 'format'],
  841. /**
  842. * Return true if the input value is valid date
  843. *
  844. * @param {BootstrapValidator} validator The validator plugin instance
  845. * @param {jQuery} $field Field element
  846. * @param {Object} options Can consist of the following keys:
  847. * - format: The date format. Default is MM/DD/YYYY
  848. * Support the following formats:
  849. * YYYY/DD/MM
  850. * YYYY/DD/MM h:m A
  851. * YYYY/MM/DD
  852. * YYYY/MM/DD h:m A
  853. *
  854. * YYYY-DD-MM
  855. * YYYY-DD-MM h:m A
  856. * YYYY-MM-DD
  857. * YYYY-MM-DD h:m A
  858. *
  859. * MM/DD/YYYY
  860. * MM/DD/YYYY h:m A
  861. * DD/MM/YYYY
  862. * DD/MM/YYYY h:m A
  863. *
  864. * MM-DD-YYYY
  865. * MM-DD-YYYY h:m A
  866. * DD-MM-YYYY
  867. * DD-MM-YYYY h:m A
  868. * - message: The invalid message
  869. * @returns {Boolean}
  870. */
  871. validate: function(validator, $field, options) {
  872. var value = $field.val();
  873. if (value == '') {
  874. return true;
  875. }
  876. // Determine the separator
  877. options.format = options.format || 'MM/DD/YYYY';
  878. var separator = (options.format.indexOf('/') != -1)
  879. ? '/'
  880. : ((options.format.indexOf('-') != -1) ? '-' : null);
  881. if (separator == null) {
  882. return false;
  883. }
  884. var month, day, year, minutes = null, hours = null, matches;
  885. switch (true) {
  886. case (separator == '/' && (matches = value.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})$/i)) && options.format == 'YYYY/DD/MM'):
  887. case (separator == '-' && (matches = value.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/i)) && options.format == 'YYYY-DD-MM'):
  888. year = matches[1]; day = matches[2]; month = matches[3];
  889. break;
  890. case (separator == '/' && (matches = value.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/i)) && options.format == 'DD/MM/YYYY'):
  891. case (separator == '-' && (matches = value.match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/i)) && options.format == 'DD-MM-YYYY'):
  892. day = matches[1]; month = matches[2]; year = matches[3];
  893. break;
  894. case (separator == '/' && (matches = value.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})$/i)) && options.format == 'YYYY/MM/DD'):
  895. case (separator == '-' && (matches = value.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/i)) && options.format == 'YYYY-MM-DD'):
  896. year = matches[1]; month = matches[2]; day = matches[3];
  897. break;
  898. case (separator == '/' && (matches = value.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/i)) && options.format == 'MM/DD/YYYY'):
  899. case (separator == '-' && (matches = value.match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/i)) && options.format == 'MM-DD-YYYY'):
  900. month = matches[1]; day = matches[2]; year = matches[3];
  901. break;
  902. case (separator == '/' && (matches = value.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{1,2})\s+(AM|PM)$/i)) && options.format == 'YYYY/DD/MM h:m A'):
  903. case (separator == '-' && (matches = value.match(/^(\d{4})-(\d{1,2})-(\d{1,2})\s+(\d{1,2}):(\d{1,2})\s+(AM|PM)$/i)) && options.format == 'YYYY-DD-MM h:m A'):
  904. year = matches[1]; day = matches[2]; month = matches[3]; hours = matches[4]; minutes = matches[5];
  905. break;
  906. case (separator == '/' && (matches = value.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})\s+(\d{1,2}):(\d{1,2})\s+(AM|PM)$/i)) && options.format == 'DD/MM/YYYY h:m A'):
  907. case (separator == '-' && (matches = value.match(/^(\d{1,2})-(\d{1,2})-(\d{4})\s+(\d{1,2}):(\d{1,2})\s+(AM|PM)$/i)) && options.format == 'DD-MM-YYYY h:m A'):
  908. day = matches[1]; month = matches[2]; year = matches[3]; hours = matches[4]; minutes = matches[5];
  909. break;
  910. case (separator == '/' && (matches = value.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{1,2})\s+(AM|PM)$/i)) && options.format == 'YYYY/MM/DD h:m A'):
  911. case (separator == '-' && (matches = value.match(/^(\d{4})-(\d{1,2})-(\d{1,2})\s+(\d{1,2}):(\d{1,2})\s+(AM|PM)$/i)) && options.format == 'YYYY-MM-DD h:m A'):
  912. year = matches[1]; month = matches[2]; day = matches[3]; hours = matches[4]; minutes = matches[5];
  913. break;
  914. case (separator == '/' && (matches = value.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})\s+(\d{1,2}):(\d{1,2})\s+(AM|PM)$/i)) && options.format == 'MM/DD/YYYY h:m A'):
  915. case (separator == '-' && (matches = value.match(/^(\d{1,2})-(\d{1,2})-(\d{4})\s+(\d{1,2}):(\d{1,2})\s+(AM|PM)$/i)) && options.format == 'MM-DD-YYYY h:m A'):
  916. month = matches[1]; day = matches[2]; year = matches[3]; hours = matches[4]; minutes = matches[5];
  917. break;
  918. default:
  919. return false;
  920. }
  921. // Validate hours and minutes
  922. if (hours && minutes) {
  923. hours = parseInt(hours, 10);
  924. minutes = parseInt(minutes, 10);
  925. if (hours < 1 || hours > 12 || minutes < 0 || minutes > 59) {
  926. return false;
  927. }
  928. }
  929. // Validate day, month, and year
  930. day = parseInt(day, 10);
  931. month = parseInt(month, 10);
  932. year = parseInt(year, 10);
  933. if (year < 1000 || year > 9999 || month == 0 || month > 12) {
  934. return false;
  935. }
  936. var numDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  937. // Update the number of days in Feb of leap year
  938. if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
  939. numDays[1] = 29;
  940. }
  941. // Check the day
  942. return (day > 0 && day <= numDays[month - 1]);
  943. }
  944. };
  945. }(window.jQuery));
  946. ;(function($) {
  947. $.fn.bootstrapValidator.validators.different = {
  948. html5Attributes: ['message', 'field'],
  949. /**
  950. * Return true if the input value is different with given field's value
  951. *
  952. * @param {BootstrapValidator} validator The validator plugin instance
  953. * @param {jQuery} $field Field element
  954. * @param {Object} options Consists of the following key:
  955. * - field: The name of field that will be used to compare with current one
  956. * - message: The invalid message
  957. * @returns {Boolean}
  958. */
  959. validate: function(validator, $field, options) {
  960. var value = $field.val();
  961. if (value == '') {
  962. return true;
  963. }
  964. var compareWith = validator.getFieldElements(options.field);
  965. if (compareWith == null) {
  966. return true;
  967. }
  968. if (value != compareWith.val()) {
  969. validator.updateStatus(compareWith, validator.STATUS_VALID, 'different');
  970. return true;
  971. } else {
  972. return false;
  973. }
  974. }
  975. };
  976. }(window.jQuery));
  977. ;(function($) {
  978. $.fn.bootstrapValidator.validators.digits = {
  979. /**
  980. * Return true if the input value contains digits only
  981. *
  982. * @param {BootstrapValidator} validator Validate plugin instance
  983. * @param {jQuery} $field Field element
  984. * @param {Object} options
  985. * @returns {Boolean}
  986. */
  987. validate: function(validator, $field, options) {
  988. var value = $field.val();
  989. if (value == '') {
  990. return true;
  991. }
  992. return /^\d+$/.test(value);
  993. }
  994. }
  995. }(window.jQuery));
  996. ;(function($) {
  997. $.fn.bootstrapValidator.validators.emailAddress = {
  998. enableByHtml5: function($field) {
  999. return ('email' == $field.attr('type'));
  1000. },
  1001. /**
  1002. * Return true if and only if the input value is a valid email address
  1003. *
  1004. * @param {BootstrapValidator} validator Validate plugin instance
  1005. * @param {jQuery} $field Field element
  1006. * @param {Object} options
  1007. * @returns {Boolean}
  1008. */
  1009. validate: function(validator, $field, options) {
  1010. var value = $field.val();
  1011. if (value == '') {
  1012. return true;
  1013. }
  1014. // Email address regular expression
  1015. // http://stackoverflow.com/questions/46155/validate-email-address-in-javascript
  1016. var emailRegExp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  1017. return emailRegExp.test(value);
  1018. }
  1019. }
  1020. }(window.jQuery));
  1021. ;(function($) {
  1022. $.fn.bootstrapValidator.validators.greaterThan = {
  1023. html5Attributes: ['message', 'value', 'inclusive'],
  1024. enableByHtml5: function($field) {
  1025. var min = $field.attr('min');
  1026. if (min) {
  1027. return {
  1028. value: min
  1029. };
  1030. }
  1031. return false;
  1032. },
  1033. /**
  1034. * Return true if the input value is greater than or equals to given number
  1035. *
  1036. * @param {BootstrapValidator} validator Validate plugin instance
  1037. * @param {jQuery} $field Field element
  1038. * @param {Object} options Can consist of the following keys:
  1039. * - value: The number used to compare to
  1040. * - inclusive [optional]: Can be true or false. Default is true
  1041. * - message: The invalid message
  1042. * @returns {Boolean}
  1043. */
  1044. validate: function(validator, $field, options) {
  1045. var value = $field.val();
  1046. if (value == '') {
  1047. return true;
  1048. }
  1049. value = parseFloat(value);
  1050. return (options.inclusive === true) ? (value > options.value) : (value >= options.value);
  1051. }
  1052. }
  1053. }(window.jQuery));
  1054. ;(function($) {
  1055. $.fn.bootstrapValidator.validators.hexColor = {
  1056. enableByHtml5: function($field) {
  1057. return ('color' == $field.attr('type'));
  1058. },
  1059. /**
  1060. * Return true if the input value is a valid hex color
  1061. *
  1062. * @param {BootstrapValidator} validator The validator plugin instance
  1063. * @param {jQuery} $field Field element
  1064. * @param {Object} options Can consist of the following keys:
  1065. * - message: The invalid message
  1066. * @returns {Boolean}
  1067. */
  1068. validate: function(validator, $field, options) {
  1069. var value = $field.val();
  1070. if (value == '') {
  1071. return true;
  1072. }
  1073. return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(value);
  1074. }
  1075. };
  1076. }(window.jQuery));
  1077. ;(function($) {
  1078. $.fn.bootstrapValidator.validators.identical = {
  1079. html5Attributes: ['message', 'field'],
  1080. /**
  1081. * Check if input value equals to value of particular one
  1082. *
  1083. * @param {BootstrapValidator} validator The validator plugin instance
  1084. * @param {jQuery} $field Field element
  1085. * @param {Object} options Consists of the following key:
  1086. * - field: The name of field that will be used to compare with current one
  1087. * @returns {Boolean}
  1088. */
  1089. validate: function(validator, $field, options) {
  1090. var value = $field.val();
  1091. if (value == '') {
  1092. return true;
  1093. }
  1094. var compareWith = validator.getFieldElements(options.field);
  1095. if (compareWith == null) {
  1096. return true;
  1097. }
  1098. if (value == compareWith.val()) {
  1099. validator.updateStatus(compareWith, validator.STATUS_VALID, 'identical');
  1100. return true;
  1101. } else {
  1102. return false;
  1103. }
  1104. }
  1105. };
  1106. }(window.jQuery));
  1107. ;(function($) {
  1108. $.fn.bootstrapValidator.validators.ip = {
  1109. html5Attributes: ['message', 'ipv4', 'ipv6'],
  1110. /**
  1111. * Return true if the input value is a IP address.
  1112. *
  1113. * @param {BootstrapValidator} validator The validator plugin instance
  1114. * @param {jQuery} $field Field element
  1115. * @param {Object} options Can consist of the following keys:
  1116. * - ipv4: Enable IPv4 validator, default to true
  1117. * - ipv6: Enable IPv6 validator, default to true
  1118. * - message: The invalid message
  1119. * @returns {Boolean}
  1120. */
  1121. validate: function(validator, $field, options) {
  1122. var value = $field.val();
  1123. if (value == '') {
  1124. return true;
  1125. }
  1126. options = $.extend({}, { ipv4: true, ipv6: true }, options);
  1127. if (options.ipv4) {
  1128. return /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(value);
  1129. } else if (options.ipv6) {
  1130. return /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/.test(str);
  1131. }
  1132. return false;
  1133. }
  1134. };
  1135. }(window.jQuery));
  1136. ;(function($) {
  1137. $.fn.bootstrapValidator.validators.isbn = {
  1138. /**
  1139. * Return true if the input value is a valid ISBN 10 or ISBN 13 number
  1140. *
  1141. * @param {BootstrapValidator} validator The validator plugin instance
  1142. * @param {jQuery} $field Field element
  1143. * @param {Object} options Can consist of the following keys:
  1144. * - message: The invalid message
  1145. * @returns {Boolean}
  1146. */
  1147. validate: function(validator, $field, options) {
  1148. var value = $field.val();
  1149. if (value == '') {
  1150. return true;
  1151. }
  1152. // Replace all special characters except digits and X
  1153. value = value.replace(/[^\dX]/gi, '');
  1154. var chars = value.split(''),
  1155. sum = 0,
  1156. checksum;
  1157. // See http://en.wikipedia.org/wiki/International_Standard_Book_Number
  1158. switch (chars.length) {
  1159. // ISBN 10
  1160. case 10:
  1161. sum = 0;
  1162. for (var i = 0; i < 9; i++) {
  1163. sum += ((10 - i) * parseInt(chars[i]));
  1164. }
  1165. checksum = 11 - (sum % 11);
  1166. if (checksum == 11) {
  1167. checksum = 0;
  1168. } else if (checksum == 10) {
  1169. checksum = 'X';
  1170. }
  1171. return (checksum == chars[9]);
  1172. // ISBN 13
  1173. case 13:
  1174. sum = 0;
  1175. for (var i = 0; i < 12; i++) {
  1176. sum += ((i % 2 == 0) ? parseInt(chars[i]) : (parseInt(chars[i]) * 3));
  1177. }
  1178. checksum = 10 - (sum % 10);
  1179. if (checksum == 10) {
  1180. checksum = '0';
  1181. }
  1182. return (checksum == chars[12]);
  1183. default:
  1184. return false;
  1185. }
  1186. }
  1187. };
  1188. }(window.jQuery));
  1189. ;(function($) {
  1190. $.fn.bootstrapValidator.validators.lessThan = {
  1191. html5Attributes: ['message', 'value', 'inclusive'],
  1192. enableByHtml5: function($field) {
  1193. var max = $field.attr('max');
  1194. if (max) {
  1195. return {
  1196. value: max
  1197. };
  1198. }
  1199. return false;
  1200. },
  1201. /**
  1202. * Return true if the input value is less than or equal to given number
  1203. *
  1204. * @param {BootstrapValidator} validator The validator plugin instance
  1205. * @param {jQuery} $field Field element
  1206. * @param {Object} options Can consist of the following keys:
  1207. * - value: The number used to compare to
  1208. * - inclusive [optional]: Can be true or false. Default is true
  1209. * - message: The invalid message
  1210. * @returns {Boolean}
  1211. */
  1212. validate: function(validator, $field, options) {
  1213. var value = $field.val();
  1214. if (value == '') {
  1215. return true;
  1216. }
  1217. value = parseFloat(value);
  1218. return (options.inclusive === false) ? (value <= options.value) : (value < options.value);
  1219. }
  1220. };
  1221. }(window.jQuery));
  1222. ;(function($) {
  1223. $.fn.bootstrapValidator.validators.mac = {
  1224. /**
  1225. * Return true if the input value is a MAC address.
  1226. *
  1227. * @param {BootstrapValidator} validator The validator plugin instance
  1228. * @param {jQuery} $field Field element
  1229. * @param {Object} options Can consist of the following keys:
  1230. * - message: The invalid message
  1231. * @returns {Boolean}
  1232. */
  1233. validate: function(validator, $field, options) {
  1234. var value = $field.val();
  1235. if (value == '') {
  1236. return true;
  1237. }
  1238. return /^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/.test(value);
  1239. }
  1240. };
  1241. }(window.jQuery));
  1242. ;(function($) {
  1243. $.fn.bootstrapValidator.validators.notEmpty = {
  1244. enableByHtml5: function($field) {
  1245. var required = $field.attr('required') + '';
  1246. return ('required' == required || 'true' == required);
  1247. },
  1248. /**
  1249. * Check if input value is empty or not
  1250. *
  1251. * @param {BootstrapValidator} validator The validator plugin instance
  1252. * @param {jQuery} $field Field element
  1253. * @param {Object} options
  1254. * @returns {Boolean}
  1255. */
  1256. validate: function(validator, $field, options) {
  1257. var type = $field.attr('type');
  1258. if ('radio' == type || 'checkbox' == type) {
  1259. return validator
  1260. .getFieldElements($field.attr('data-bv-field'))
  1261. .filter(':checked')
  1262. .length > 0;
  1263. }
  1264. return $.trim($field.val()) != '';
  1265. }
  1266. };
  1267. }(window.jQuery));
  1268. ;(function($) {
  1269. $.fn.bootstrapValidator.validators.phone = {
  1270. html5Attributes: ['message', 'country'],
  1271. /**
  1272. * Return true if the input value contains a valid US phone number only
  1273. *
  1274. * @param {BootstrapValidator} validator Validate plugin instance
  1275. * @param {jQuery} $field Field element
  1276. * @param {Object} options Consist of key:
  1277. * - message: The invalid message
  1278. * - country: The ISO 3166 country code
  1279. * Currently it only supports United State (US) country
  1280. * @returns {Boolean}
  1281. */
  1282. validate: function(validator, $field, options) {
  1283. var value = $field.val();
  1284. if (value == '') {
  1285. return true;
  1286. }
  1287. options.country = options.country || 'US';
  1288. switch (options.country.toUpperCase()) {
  1289. case 'US':
  1290. default:
  1291. value = value.replace(/\(|\)|\s+/g, '');
  1292. return (/^(?:1\-?)?(\d{3})[\-\.]?(\d{3})[\-\.]?(\d{4})$/).test(value);
  1293. }
  1294. }
  1295. }
  1296. }(window.jQuery));
  1297. ;(function($) {
  1298. $.fn.bootstrapValidator.validators.regexp = {
  1299. html5Attributes: ['message', 'regexp'],
  1300. enableByHtml5: function($field) {
  1301. var pattern = $field.attr('pattern');
  1302. if (pattern) {
  1303. return {
  1304. regexp: pattern
  1305. };
  1306. }
  1307. return false;
  1308. },
  1309. /**
  1310. * Check if the element value matches given regular expression
  1311. *
  1312. * @param {BootstrapValidator} validator The validator plugin instance
  1313. * @param {jQuery} $field Field element
  1314. * @param {Object} options Consists of the following key:
  1315. * - regexp: The regular expression you need to check
  1316. * @returns {Boolean}
  1317. */
  1318. validate: function(validator, $field, options) {
  1319. var value = $field.val();
  1320. if (value == '') {
  1321. return true;
  1322. }
  1323. var regexp = ('string' == typeof options.regexp) ? new RegExp(options.regexp) : options.regexp;
  1324. return regexp.test(value);
  1325. }
  1326. };
  1327. }(window.jQuery));
  1328. ;(function($) {
  1329. $.fn.bootstrapValidator.validators.remote = {
  1330. html5Attributes: ['message', 'url'],
  1331. /**
  1332. * Request a remote server to check the input value
  1333. *
  1334. * @param {BootstrapValidator} validator Plugin instance
  1335. * @param {jQuery} $field Field element
  1336. * @param {Object} options Can consist of the following keys:
  1337. * - url
  1338. * - data [optional]: By default, it will take the value
  1339. * {
  1340. * <fieldName>: <fieldValue>
  1341. * }
  1342. * - message: The invalid message
  1343. * @returns {Boolean|Deferred}
  1344. */
  1345. validate: function(validator, $field, options) {
  1346. var value = $field.val();
  1347. if (value == '') {
  1348. return true;
  1349. }
  1350. var name = $field.attr('data-bv-field'), data = options.data;
  1351. if (data == null) {
  1352. data = {};
  1353. }
  1354. // Support dynamic data
  1355. if ('function' == typeof data) {
  1356. data = data.call(this, validator);
  1357. }
  1358. data[name] = value;
  1359. var dfd = new $.Deferred();
  1360. var xhr = $.ajax({
  1361. type: 'POST',
  1362. url: options.url,
  1363. dataType: 'json',
  1364. data: data
  1365. });
  1366. xhr.then(function(response) {
  1367. dfd.resolve(response.valid === true || response.valid === 'true', 'remote');
  1368. });
  1369. dfd.fail(function() {
  1370. xhr.abort();
  1371. });
  1372. return dfd;
  1373. }
  1374. };
  1375. }(window.jQuery));
  1376. ;(function($) {
  1377. $.fn.bootstrapValidator.validators.step = {
  1378. /**
  1379. * Return true if the input value is valid step one
  1380. *
  1381. * @param {BootstrapValidator} validator The validator plugin instance
  1382. * @param {jQuery} $field Field element
  1383. * @param {Object} options Can consist of the following keys:
  1384. * - baseValue: The base value
  1385. * - step: The step
  1386. * - message: The invalid message
  1387. * @returns {Boolean}
  1388. */
  1389. validate: function(validator, $field, options) {
  1390. var value = $field.val();
  1391. if (value == '') {
  1392. return true;
  1393. }
  1394. options = $.extend({}, { baseValue: 0, step: 1 }, options);
  1395. value = parseFloat(value);
  1396. if (isNaN(value) || !isFinite(value)) {
  1397. return false;
  1398. }
  1399. var round = function(x, precision) {
  1400. var m = Math.pow(10, precision);
  1401. x = x * m;
  1402. var sign = (x > 0) | -(x < 0),
  1403. isHalf = (x % 1 === 0.5 * sign);
  1404. if (isHalf) {
  1405. return (Math.floor(x) + (sign > 0)) / m;
  1406. } else {
  1407. return Math.round(x) / m;
  1408. }
  1409. },
  1410. floatMod = function(x, y) {
  1411. if (y == 0.0) {
  1412. return 1.0;
  1413. }
  1414. var dotX = (x + '').split('.'),
  1415. dotY = (y + '').split('.'),
  1416. precision = ((dotX.length == 1) ? 0 : dotX[1].length) + ((dotY.length == 1) ? 0 : dotY[1].length);
  1417. return round(x - y * Math.floor(x / y), precision);
  1418. };
  1419. var mod = floatMod(value - options.baseValue, options.step);
  1420. return (mod == 0.0 || mod == options.step);
  1421. }
  1422. };
  1423. }(window.jQuery));
  1424. ;(function($) {
  1425. $.fn.bootstrapValidator.validators.stringLength = {
  1426. html5Attributes: ['message', 'min', 'max'],
  1427. enableByHtml5: function($field) {
  1428. var maxLength = $field.attr('maxlength');
  1429. if (maxLength) {
  1430. return {
  1431. max: parseInt(maxLength, 10)
  1432. };
  1433. }
  1434. return true;
  1435. },
  1436. /**
  1437. * Check if the length of element value is less or more than given number
  1438. *
  1439. * @param {BootstrapValidator} validator The validator plugin instance
  1440. * @param {jQuery} $field Field element
  1441. * @param {Object} options Consists of following keys:
  1442. * - min
  1443. * - max
  1444. * At least one of two keys is required
  1445. * @returns {Boolean}
  1446. */
  1447. validate: function(validator, $field, options) {
  1448. var value = $field.val();
  1449. if (value == '') {
  1450. return true;
  1451. }
  1452. var length = $.trim(value).length;
  1453. if ((options.min && length < options.min) || (options.max && length > options.max)) {
  1454. return false;
  1455. }
  1456. return true;
  1457. }
  1458. };
  1459. }(window.jQuery));
  1460. ;(function($) {
  1461. $.fn.bootstrapValidator.validators.uri = {
  1462. enableByHtml5: function($field) {
  1463. return ('url' == $field.attr('type'));
  1464. },
  1465. /**
  1466. * Return true if the input value is a valid URL
  1467. *
  1468. * @param {BootstrapValidator} validator The validator plugin instance
  1469. * @param {jQuery} $field Field element
  1470. * @param {Object} options
  1471. * @returns {Boolean}
  1472. */
  1473. validate: function(validator, $field, options) {
  1474. var value = $field.val();
  1475. if (value == '') {
  1476. return true;
  1477. }
  1478. // Credit to https://gist.github.com/dperini/729294
  1479. //
  1480. // Regular Expression for URL validation
  1481. //
  1482. // Author: Diego Perini
  1483. // Updated: 2010/12/05
  1484. //
  1485. // the regular expression composed & commented
  1486. // could be easily tweaked for RFC compliance,
  1487. // it was expressly modified to fit & satisfy
  1488. // these test for an URL shortener:
  1489. //
  1490. // http://mathiasbynens.be/demo/url-regex
  1491. //
  1492. // Notes on possible differences from a standard/generic validation:
  1493. //
  1494. // - utf-8 char class take in consideration the full Unicode range
  1495. // - TLDs have been made mandatory so single names like "localhost" fails
  1496. // - protocols have been restricted to ftp, http and https only as requested
  1497. //
  1498. // Changes:
  1499. //
  1500. // - IP address dotted notation validation, range: 1.0.0.0 - 223.255.255.255
  1501. // first and last IP address of each class is considered invalid
  1502. // (since they are broadcast/network addresses)
  1503. //
  1504. // - Added exclusion of private, reserved and/or local networks ranges
  1505. //
  1506. // Compressed one-line versions:
  1507. //
  1508. // Javascript version
  1509. //
  1510. // /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/i
  1511. //
  1512. // PHP version
  1513. //
  1514. // _^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:/[^\s]*)?$_iuS
  1515. var urlExp = new RegExp(
  1516. "^" +
  1517. // protocol identifier
  1518. "(?:(?:https?|ftp)://)" +
  1519. // user:pass authentication
  1520. "(?:\\S+(?::\\S*)?@)?" +
  1521. "(?:" +
  1522. // IP address exclusion
  1523. // private & local networks
  1524. "(?!10(?:\\.\\d{1,3}){3})" +
  1525. "(?!127(?:\\.\\d{1,3}){3})" +
  1526. "(?!169\\.254(?:\\.\\d{1,3}){2})" +
  1527. "(?!192\\.168(?:\\.\\d{1,3}){2})" +
  1528. "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" +
  1529. // IP address dotted notation octets
  1530. // excludes loopback network 0.0.0.0
  1531. // excludes reserved space >= 224.0.0.0
  1532. // excludes network & broacast addresses
  1533. // (first & last IP address of each class)
  1534. "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
  1535. "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
  1536. "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
  1537. "|" +
  1538. // host name
  1539. "(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)" +
  1540. // domain name
  1541. "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*" +
  1542. // TLD identifier
  1543. "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" +
  1544. ")" +
  1545. // port number
  1546. "(?::\\d{2,5})?" +
  1547. // resource path
  1548. "(?:/[^\\s]*)?" +
  1549. "$", "i"
  1550. );
  1551. return urlExp.test(value);
  1552. }
  1553. };
  1554. }(window.jQuery));
  1555. ;(function($) {
  1556. $.fn.bootstrapValidator.validators.zipCode = {
  1557. html5Attributes: ['message', 'country'],
  1558. /**
  1559. * Return true if and only if the input value is a valid country zip code
  1560. *
  1561. * @param {BootstrapValidator} validator The validator plugin instance
  1562. * @param {jQuery} $field Field element
  1563. * @param {Object} options Consist of key:
  1564. * - message: The invalid message
  1565. * - country: The ISO 3166 country code
  1566. *
  1567. * Currently it supports the following countries:
  1568. * - US (United State)
  1569. * - DK (Denmark)
  1570. * - SE (Sweden)
  1571. * @returns {Boolean}
  1572. */
  1573. validate: function(validator, $field, options) {
  1574. var value = $field.val();
  1575. if (value == '' || !options.country) {
  1576. return true;
  1577. }
  1578. options.country = options.country || 'US';
  1579. switch (options.country.toUpperCase()) {
  1580. case 'DK':
  1581. return /^(DK(-|\s)?)?\d{4}$/i.test(value);
  1582. case 'SE':
  1583. return /^(S-)?\d{3}\s?\d{2}$/i.test(value);
  1584. case 'US':
  1585. default:
  1586. return /^\d{5}([\-]\d{4})?$/.test(value);
  1587. }
  1588. }
  1589. };
  1590. }(window.jQuery));