bootstrapValidator.js 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  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.3.2-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. if (this.options.fields == null) {
  81. return;
  82. }
  83. var that = this;
  84. this.$form
  85. // Disable client side validation in HTML 5
  86. .attr('novalidate', 'novalidate')
  87. .addClass(this.options.elementClass)
  88. // Disable the default submission first
  89. .on('submit.bootstrapValidator', function(e) {
  90. e.preventDefault();
  91. that.validate();
  92. })
  93. .find(this.options.submitButtons)
  94. .on('click', function() {
  95. that.$submitButton = $(this);
  96. });
  97. for (var field in this.options.fields) {
  98. this._initField(field);
  99. }
  100. this._setLiveValidating();
  101. },
  102. /**
  103. * Init field
  104. *
  105. * @param {String} field The field name
  106. */
  107. _initField: function(field) {
  108. if (this.options.fields[field] == null || this.options.fields[field].validators == null) {
  109. return;
  110. }
  111. this.dfds[field] = {};
  112. this.results[field] = {};
  113. var fields = this.getFieldElements(field);
  114. // We don't need to validate non-existing fields
  115. if (fields == null) {
  116. delete this.options.fields[field];
  117. delete this.dfds[field];
  118. return;
  119. }
  120. // Create help block elements for showing the error messages
  121. var $field = $(fields[0]),
  122. $parent = $field.parents('.form-group'),
  123. // Allow user to indicate where the error messages are shown
  124. $message = this.options.fields[field].container ? $parent.find(this.options.fields[field].container) : this._getMessageContainer($field);
  125. $field.data('bootstrapValidator.messageContainer', $message);
  126. for (var validatorName in this.options.fields[field].validators) {
  127. if (!$.fn.bootstrapValidator.validators[validatorName]) {
  128. delete this.options.fields[field].validators[validatorName];
  129. continue;
  130. }
  131. this.results[field][validatorName] = this.STATUS_NOT_VALIDATED;
  132. $('<small/>')
  133. .css('display', 'none')
  134. .attr('data-bv-validator', validatorName)
  135. .html(this.options.fields[field].validators[validatorName].message || this.options.message)
  136. .addClass('help-block')
  137. .appendTo($message);
  138. }
  139. // Prepare the feedback icons
  140. // Available from Bootstrap 3.1 (http://getbootstrap.com/css/#forms-control-validation)
  141. if (this.options.feedbackIcons
  142. && this.options.feedbackIcons.validating && this.options.feedbackIcons.invalid && this.options.feedbackIcons.valid)
  143. {
  144. $parent.addClass('has-feedback');
  145. var $icon = $('<i/>').css('display', 'none').addClass('form-control-feedback').attr('data-bv-field', field).insertAfter($(fields[fields.length - 1]));
  146. // The feedback icon does not render correctly if there is no label
  147. // https://github.com/twbs/bootstrap/issues/12873
  148. if ($parent.find('label').length == 0) {
  149. $icon.css('top', 0);
  150. }
  151. }
  152. if (this.options.fields[field]['enabled'] == null) {
  153. this.options.fields[field]['enabled'] = true;
  154. }
  155. // Whenever the user change the field value, mark it as not validated yet
  156. var that = this,
  157. type = fields.attr('type'),
  158. event = ('radio' == type || 'checkbox' == type || 'SELECT' == fields[0].tagName) ? 'change' : 'keyup';
  159. fields.on(event, function() {
  160. that.updateStatus($field, that.STATUS_NOT_VALIDATED, null);
  161. });
  162. },
  163. /**
  164. * Get the element to place the error messages
  165. *
  166. * @param {jQuery} $field The field element
  167. * @returns {jQuery}
  168. */
  169. _getMessageContainer: function($field) {
  170. var $parent = $field.parent();
  171. if ($parent.hasClass('form-group')) {
  172. return $parent;
  173. }
  174. var cssClasses = $parent.attr('class');
  175. if (!cssClasses) {
  176. return this._getMessageContainer($parent);
  177. }
  178. cssClasses = cssClasses.split(' ');
  179. var n = cssClasses.length;
  180. for (var i = 0; i < n; i++) {
  181. if (/^col-(xs|sm|md|lg)-\d+$/.test(cssClasses[i]) || /^col-(xs|sm|md|lg)-offset-\d+$/.test(cssClasses[i])) {
  182. return $parent;
  183. }
  184. }
  185. return this._getMessageContainer($parent);
  186. },
  187. /**
  188. * Enable live validating
  189. */
  190. _setLiveValidating: function() {
  191. if ('enabled' == this.options.live) {
  192. var that = this;
  193. for (var field in this.options.fields) {
  194. (function(f) {
  195. var fields = that.getFieldElements(f);
  196. if (fields) {
  197. var type = fields.attr('type'),
  198. event = ('radio' == type || 'checkbox' == type || 'SELECT' == fields[0].tagName) ? 'change' : 'keyup';
  199. fields.on(event, function() {
  200. that.validateField(f);
  201. });
  202. }
  203. })(field);
  204. }
  205. }
  206. },
  207. /**
  208. * Disable/Enable submit buttons
  209. *
  210. * @param {Boolean} disabled
  211. */
  212. _disableSubmitButtons: function(disabled) {
  213. if (!disabled) {
  214. this.$form.find(this.options.submitButtons).removeAttr('disabled');
  215. } else if (this.options.live != 'disabled') {
  216. // Don't disable if the live validating mode is disabled
  217. this.$form.find(this.options.submitButtons).attr('disabled', 'disabled');
  218. }
  219. },
  220. /**
  221. * Called when all validations are completed
  222. */
  223. _submit: function() {
  224. if (!this.isValid()) {
  225. if ('submitted' == this.options.live) {
  226. this.options.live = 'enabled';
  227. this._setLiveValidating();
  228. }
  229. // Focus to the first invalid field
  230. if (this.invalidField) {
  231. this.getFieldElements(this.invalidField).focus();
  232. }
  233. return;
  234. }
  235. this._disableSubmitButtons(true);
  236. // Call the custom submission if enabled
  237. if (this.options.submitHandler && 'function' == typeof this.options.submitHandler) {
  238. this.options.submitHandler.call(this, this, this.$form, this.$submitButton);
  239. } else {
  240. // Submit form
  241. this.$form.off('submit.bootstrapValidator').submit();
  242. }
  243. },
  244. // --- Public methods ---
  245. /**
  246. * Retrieve the field elements by given name
  247. *
  248. * @param {String} field The field name
  249. * @returns {null|jQuery[]}
  250. */
  251. getFieldElements: function(field) {
  252. var fields = this.$form.find('[name="' + field + '"]');
  253. return (fields.length == 0) ? null : fields;
  254. },
  255. /**
  256. * Validate the form
  257. *
  258. * @return {BootstrapValidator}
  259. */
  260. validate: function() {
  261. if (!this.options.fields) {
  262. return this;
  263. }
  264. this._disableSubmitButtons(true);
  265. for (var field in this.options.fields) {
  266. this.validateField(field);
  267. }
  268. this._submit();
  269. return this;
  270. },
  271. /**
  272. * Validate given field
  273. *
  274. * @param {String} field The field name
  275. */
  276. validateField: function(field) {
  277. if (!this.options.fields[field]['enabled']) {
  278. return;
  279. }
  280. var that = this,
  281. fields = this.getFieldElements(field),
  282. $field = $(fields[0]),
  283. validators = this.options.fields[field].validators,
  284. validatorName,
  285. validateResult;
  286. // We don't need to validate disabled field
  287. if (fields.length == 1 && fields.is(':disabled')) {
  288. delete this.options.fields[field];
  289. delete this.dfds[field];
  290. return;
  291. }
  292. for (validatorName in validators) {
  293. if (this.dfds[field][validatorName]) {
  294. this.dfds[field][validatorName].reject();
  295. }
  296. // Don't validate field if it is already done
  297. if (this.results[field][validatorName] == this.STATUS_VALID || this.results[field][validatorName] == this.STATUS_INVALID) {
  298. continue;
  299. }
  300. this.results[field][validatorName] = this.STATUS_VALIDATING;
  301. validateResult = $.fn.bootstrapValidator.validators[validatorName].validate(this, $field, validators[validatorName]);
  302. if ('object' == typeof validateResult) {
  303. this.updateStatus($field, this.STATUS_VALIDATING, validatorName);
  304. this.dfds[field][validatorName] = validateResult;
  305. validateResult.done(function(isValid, v) {
  306. // v is validator name
  307. delete that.dfds[field][v];
  308. that.updateStatus($field, isValid ? that.STATUS_VALID : that.STATUS_INVALID, v);
  309. if (isValid && 'disabled' == that.options.live) {
  310. that._submit();
  311. }
  312. });
  313. } else if ('boolean' == typeof validateResult) {
  314. this.updateStatus($field, validateResult ? this.STATUS_VALID : this.STATUS_INVALID, validatorName);
  315. }
  316. }
  317. },
  318. /**
  319. * Check the form validity
  320. *
  321. * @returns {Boolean}
  322. */
  323. isValid: function() {
  324. var field, validatorName;
  325. for (field in this.results) {
  326. if (!this.options.fields[field]['enabled']) {
  327. continue;
  328. }
  329. for (validatorName in this.results[field]) {
  330. if (this.results[field][validatorName] == this.STATUS_NOT_VALIDATED || this.results[field][validatorName] == this.STATUS_VALIDATING) {
  331. return false;
  332. }
  333. if (this.results[field][validatorName] == this.STATUS_INVALID) {
  334. this.invalidField = field;
  335. return false;
  336. }
  337. }
  338. }
  339. return true;
  340. },
  341. /**
  342. * Update field status
  343. *
  344. * @param {String|jQuery} field The field name or field element
  345. * @param {String} status The status
  346. * Can be 'NOT_VALIDATED', 'VALIDATING', 'INVALID' or 'VALID'
  347. * @param {String|null} validatorName The validator name. If null, the method updates validity result for all validators
  348. * @return {BootstrapValidator}
  349. */
  350. updateStatus: function(field, status, validatorName) {
  351. var $field = ('string' == typeof field) ? this.getFieldElements(field) : field,
  352. that = this,
  353. field = $field.attr('name'),
  354. $parent = $field.parents('.form-group'),
  355. $message = $field.data('bootstrapValidator.messageContainer'),
  356. $errors = $message.find('.help-block[data-bv-validator]'),
  357. $icon = $parent.find('.form-control-feedback[data-bv-field="' + field + '"]');
  358. // Update status
  359. if (validatorName) {
  360. this.results[field][validatorName] = status;
  361. } else {
  362. for (var v in this.options.fields[field].validators) {
  363. this.results[field][v] = status;
  364. }
  365. }
  366. // Show/hide error elements and feedback icons
  367. switch (status) {
  368. case this.STATUS_VALIDATING:
  369. this._disableSubmitButtons(true);
  370. $parent.removeClass('has-success').removeClass('has-error');
  371. // TODO: Show validating message
  372. validatorName ? $errors.filter('.help-block[data-bv-validator="' + validatorName + '"]').hide() : $errors.hide();
  373. if ($icon) {
  374. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).addClass(this.options.feedbackIcons.validating).show();
  375. }
  376. break;
  377. case this.STATUS_INVALID:
  378. this._disableSubmitButtons(true);
  379. $parent.removeClass('has-success').addClass('has-error');
  380. validatorName ? $errors.filter('[data-bv-validator="' + validatorName + '"]').show() : $errors.show();
  381. if ($icon) {
  382. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.validating).addClass(this.options.feedbackIcons.invalid).show();
  383. }
  384. break;
  385. case this.STATUS_VALID:
  386. validatorName ? $errors.filter('[data-bv-validator="' + validatorName + '"]').hide() : $errors.hide();
  387. // If the field is valid
  388. if ($errors.filter(function() {
  389. var display = $(this).css('display'), v = $(this).attr('data-bv-validator');
  390. return ('block' == display) || (that.results[field][v] != that.STATUS_VALID);
  391. }).length == 0
  392. ) {
  393. this._disableSubmitButtons(false);
  394. $parent.removeClass('has-error').addClass('has-success');
  395. if ($icon) {
  396. $icon.removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).addClass(this.options.feedbackIcons.valid).show();
  397. }
  398. }
  399. break;
  400. case this.STATUS_NOT_VALIDATED:
  401. default:
  402. this._disableSubmitButtons(false);
  403. $parent.removeClass('has-success').removeClass('has-error');
  404. validatorName ? $errors.filter('.help-block[data-bv-validator="' + validatorName + '"]').hide() : $errors.hide();
  405. if ($icon) {
  406. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).hide();
  407. }
  408. break;
  409. }
  410. return this;
  411. },
  412. // Useful APIs which aren't used internally
  413. /**
  414. * Reset the form
  415. *
  416. * @param {Boolean} resetFormData Reset current form data
  417. * @return {BootstrapValidator}
  418. */
  419. resetForm: function(resetFormData) {
  420. var field, $field, type;
  421. for (field in this.options.fields) {
  422. this.dfds[field] = {};
  423. this.results[field] = {};
  424. $field = this.getFieldElements(field);
  425. // Mark field as not validated yet
  426. this.updateStatus($field, this.STATUS_NOT_VALIDATED, null);
  427. if (resetFormData) {
  428. type = $field.attr('type');
  429. ('radio' == type || 'checkbox' == type) ? $field.removeAttr('checked').removeAttr('selected') : $field.val('');
  430. }
  431. }
  432. this.invalidField = null;
  433. this.$submitButton = null;
  434. // Enable submit buttons
  435. this._disableSubmitButtons(false);
  436. return this;
  437. },
  438. /**
  439. * Enable/Disable all validators to given field
  440. *
  441. * @param {String} field The field name
  442. * @param {Boolean} enabled Enable/Disable field validators
  443. * @return {BootstrapValidator}
  444. */
  445. enableFieldValidators: function(field, enabled) {
  446. this.options.fields[field]['enabled'] = enabled;
  447. this.updateStatus(field, this.STATUS_NOT_VALIDATED, null);
  448. return this;
  449. }
  450. };
  451. // Plugin definition
  452. $.fn.bootstrapValidator = function(options) {
  453. return this.each(function() {
  454. var $this = $(this), data = $this.data('bootstrapValidator');
  455. if (!data) {
  456. $this.data('bootstrapValidator', (data = new BootstrapValidator(this, options)));
  457. }
  458. if ('string' == typeof options) {
  459. data[options]();
  460. }
  461. });
  462. };
  463. // Available validators
  464. $.fn.bootstrapValidator.validators = {};
  465. $.fn.bootstrapValidator.Constructor = BootstrapValidator;
  466. }(window.jQuery));
  467. ;(function($) {
  468. $.fn.bootstrapValidator.validators.between = {
  469. /**
  470. * Return true if the input value is between (strictly or not) two given numbers
  471. *
  472. * @param {BootstrapValidator} validator The validator plugin instance
  473. * @param {jQuery} $field Field element
  474. * @param {Object} options Can consist of the following keys:
  475. * - min
  476. * - max
  477. * - inclusive [optional]: Can be true or false. Default is true
  478. * - message: The invalid message
  479. * @returns {Boolean}
  480. */
  481. validate: function(validator, $field, options) {
  482. var value = $field.val();
  483. if (value == '') {
  484. return true;
  485. }
  486. value = parseFloat(value);
  487. return (options.inclusive === true)
  488. ? (value > options.min && value < options.max)
  489. : (value >= options.min && value <= options.max);
  490. }
  491. };
  492. }(window.jQuery));
  493. ;(function($) {
  494. $.fn.bootstrapValidator.validators.callback = {
  495. /**
  496. * Return result from the callback method
  497. *
  498. * @param {BootstrapValidator} validator The validator plugin instance
  499. * @param {jQuery} $field Field element
  500. * @param {Object} options Can consist of the following keys:
  501. * - callback: The callback method that passes 2 parameters:
  502. * callback: function(fieldValue, validator) {
  503. * // fieldValue is the value of field
  504. * // validator is instance of BootstrapValidator
  505. * }
  506. * - message: The invalid message
  507. * @returns {Boolean|Deferred}
  508. */
  509. validate: function(validator, $field, options) {
  510. var value = $field.val();
  511. if (options.callback && 'function' == typeof options.callback) {
  512. var dfd = new $.Deferred();
  513. dfd.resolve(options.callback.call(this, value, validator), 'callback');
  514. return dfd;
  515. }
  516. return true;
  517. }
  518. };
  519. }(window.jQuery));
  520. ;(function($) {
  521. $.fn.bootstrapValidator.validators.choice = {
  522. /**
  523. * Check if the number of checked boxes are less or more than a given number
  524. *
  525. * @param {BootstrapValidator} validator The validator plugin instance
  526. * @param {jQuery} $field Field element
  527. * @param {Object} options Consists of following keys:
  528. * - min
  529. * - max
  530. * At least one of two keys is required
  531. * @returns {Boolean}
  532. */
  533. validate: function(validator, $field, options) {
  534. var numChoices = validator
  535. .getFieldElements($field.attr('name'))
  536. .filter(':checked')
  537. .length;
  538. if ((options.min && numChoices < options.min) || (options.max && numChoices > options.max)) {
  539. return false;
  540. }
  541. return true;
  542. }
  543. };
  544. }(window.jQuery));
  545. ;(function($) {
  546. $.fn.bootstrapValidator.validators.creditCard = {
  547. /**
  548. * Return true if the input value is valid credit card number
  549. * Based on https://gist.github.com/DiegoSalazar/4075533
  550. *
  551. * @param {BootstrapValidator} validator The validator plugin instance
  552. * @param {jQuery} $field Field element
  553. * @param {Object} options Can consist of the following key:
  554. * - message: The invalid message
  555. * @returns {Boolean}
  556. */
  557. validate: function(validator, $field, options) {
  558. var value = $field.val();
  559. if (value == '') {
  560. return true;
  561. }
  562. // Accept only digits, dashes or spaces
  563. if (/[^0-9-\s]+/.test(value)) {
  564. return false;
  565. }
  566. // The Luhn Algorithm
  567. // http://en.wikipedia.org/wiki/Luhn
  568. value = value.replace(/\D/g, '');
  569. var check = 0, digit = 0, even = false, length = value.length;
  570. for (var n = length - 1; n >= 0; n--) {
  571. digit = parseInt(value.charAt(n), 10);
  572. if (even) {
  573. if ((digit *= 2) > 9) {
  574. digit -= 9;
  575. }
  576. }
  577. check += digit;
  578. even = !even;
  579. }
  580. return (check % 10) == 0;
  581. }
  582. };
  583. }(window.jQuery));
  584. ;(function($) {
  585. $.fn.bootstrapValidator.validators.date = {
  586. /**
  587. * Return true if the input value is valid date
  588. *
  589. * @param {BootstrapValidator} validator The validator plugin instance
  590. * @param {jQuery} $field Field element
  591. * @param {Object} options Can consist of the following keys:
  592. * - format: The date format. Default is MM/DD/YYYY
  593. * Support the following formats:
  594. * YYYY/DD/MM
  595. * YYYY/DD/MM h:m A
  596. * YYYY/MM/DD
  597. * YYYY/MM/DD h:m A
  598. *
  599. * YYYY-DD-MM
  600. * YYYY-DD-MM h:m A
  601. * YYYY-MM-DD
  602. * YYYY-MM-DD h:m A
  603. *
  604. * MM/DD/YYYY
  605. * MM/DD/YYYY h:m A
  606. * DD/MM/YYYY
  607. * DD/MM/YYYY h:m A
  608. *
  609. * MM-DD-YYYY
  610. * MM-DD-YYYY h:m A
  611. * DD-MM-YYYY
  612. * DD-MM-YYYY h:m A
  613. * - message: The invalid message
  614. * @returns {Boolean}
  615. */
  616. validate: function(validator, $field, options) {
  617. var value = $field.val();
  618. if (value == '') {
  619. return true;
  620. }
  621. // Determine the separator
  622. options.format = options.format || 'MM/DD/YYYY';
  623. var separator = (options.format.indexOf('/') != -1)
  624. ? '/'
  625. : ((options.format.indexOf('-') != -1) ? '-' : null);
  626. if (separator == null) {
  627. return false;
  628. }
  629. var month, day, year, minutes = null, hours = null, matches;
  630. switch (true) {
  631. case (separator == '/' && (matches = value.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})$/i)) && options.format == 'YYYY/DD/MM'):
  632. case (separator == '-' && (matches = value.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/i)) && options.format == 'YYYY-DD-MM'):
  633. year = matches[1]; day = matches[2]; month = matches[3];
  634. break;
  635. case (separator == '/' && (matches = value.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/i)) && options.format == 'DD/MM/YYYY'):
  636. case (separator == '-' && (matches = value.match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/i)) && options.format == 'DD-MM-YYYY'):
  637. day = matches[1]; month = matches[2]; year = matches[3];
  638. break;
  639. case (separator == '/' && (matches = value.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})$/i)) && options.format == 'YYYY/MM/DD'):
  640. case (separator == '-' && (matches = value.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/i)) && options.format == 'YYYY-MM-DD'):
  641. year = matches[1]; month = matches[2]; day = matches[3];
  642. break;
  643. case (separator == '/' && (matches = value.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/i)) && options.format == 'MM/DD/YYYY'):
  644. case (separator == '-' && (matches = value.match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/i)) && options.format == 'MM-DD-YYYY'):
  645. month = matches[1]; day = matches[2]; year = matches[3];
  646. break;
  647. 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'):
  648. 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'):
  649. year = matches[1]; day = matches[2]; month = matches[3]; hours = matches[4]; minutes = matches[5];
  650. break;
  651. 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'):
  652. 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'):
  653. day = matches[1]; month = matches[2]; year = matches[3]; hours = matches[4]; minutes = matches[5];
  654. break;
  655. 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'):
  656. 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'):
  657. year = matches[1]; month = matches[2]; day = matches[3]; hours = matches[4]; minutes = matches[5];
  658. break;
  659. 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'):
  660. 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'):
  661. month = matches[1]; day = matches[2]; year = matches[3]; hours = matches[4]; minutes = matches[5];
  662. break;
  663. default:
  664. return false;
  665. }
  666. // Validate hours and minutes
  667. if (hours && minutes) {
  668. hours = parseInt(hours, 10);
  669. minutes = parseInt(minutes, 10);
  670. if (hours < 1 || hours > 12 || minutes < 0 || minutes > 59) {
  671. return false;
  672. }
  673. }
  674. // Validate day, month, and year
  675. day = parseInt(day, 10);
  676. month = parseInt(month, 10);
  677. year = parseInt(year, 10);
  678. if (year < 1000 || year > 9999 || month == 0 || month > 12) {
  679. return false;
  680. }
  681. var numDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  682. // Update the number of days in Feb of leap year
  683. if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
  684. numDays[1] = 29;
  685. }
  686. // Check the day
  687. return (day > 0 && day <= numDays[month - 1]);
  688. }
  689. };
  690. }(window.jQuery));
  691. ;(function($) {
  692. $.fn.bootstrapValidator.validators.different = {
  693. /**
  694. * Return true if the input value is different with given field's value
  695. *
  696. * @param {BootstrapValidator} validator The validator plugin instance
  697. * @param {jQuery} $field Field element
  698. * @param {Object} options Consists of the following key:
  699. * - field: The name of field that will be used to compare with current one
  700. * @returns {Boolean}
  701. */
  702. validate: function(validator, $field, options) {
  703. var value = $field.val();
  704. if (value == '') {
  705. return true;
  706. }
  707. var compareWith = validator.getFieldElements(options.field);
  708. if (compareWith == null) {
  709. return true;
  710. }
  711. if (value != compareWith.val()) {
  712. validator.updateStatus(compareWith, validator.STATUS_VALID, 'different');
  713. return true;
  714. } else {
  715. return false;
  716. }
  717. }
  718. };
  719. }(window.jQuery));
  720. ;(function($) {
  721. $.fn.bootstrapValidator.validators.digits = {
  722. /**
  723. * Return true if the input value contains digits only
  724. *
  725. * @param {BootstrapValidator} validator Validate plugin instance
  726. * @param {jQuery} $field Field element
  727. * @param {Object} options
  728. * @returns {Boolean}
  729. */
  730. validate: function(validator, $field, options) {
  731. var value = $field.val();
  732. if (value == '') {
  733. return true;
  734. }
  735. return /^\d+$/.test(value);
  736. }
  737. }
  738. }(window.jQuery));
  739. ;(function($) {
  740. $.fn.bootstrapValidator.validators.emailAddress = {
  741. /**
  742. * Return true if and only if the input value is a valid email address
  743. *
  744. * @param {BootstrapValidator} validator Validate plugin instance
  745. * @param {jQuery} $field Field element
  746. * @param {Object} options
  747. * @returns {Boolean}
  748. */
  749. validate: function(validator, $field, options) {
  750. var value = $field.val();
  751. if (value == '') {
  752. return true;
  753. }
  754. // Email address regular expression
  755. // http://stackoverflow.com/questions/46155/validate-email-address-in-javascript
  756. 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,}))$/;
  757. return emailRegExp.test(value);
  758. }
  759. }
  760. }(window.jQuery));
  761. ;(function($) {
  762. $.fn.bootstrapValidator.validators.greaterThan = {
  763. /**
  764. * Return true if the input value is greater than or equals to given number
  765. *
  766. * @param {BootstrapValidator} validator Validate plugin instance
  767. * @param {jQuery} $field Field element
  768. * @param {Object} options Can consist of the following keys:
  769. * - value: The number used to compare to
  770. * - inclusive [optional]: Can be true or false. Default is true
  771. * - message: The invalid message
  772. * @returns {Boolean}
  773. */
  774. validate: function(validator, $field, options) {
  775. var value = $field.val();
  776. if (value == '') {
  777. return true;
  778. }
  779. value = parseFloat(value);
  780. return (options.inclusive === true) ? (value > options.value) : (value >= options.value);
  781. }
  782. }
  783. }(window.jQuery));
  784. ;(function($) {
  785. $.fn.bootstrapValidator.validators.hexColor = {
  786. /**
  787. * Return true if the input value is a valid hex color
  788. *
  789. * @param {BootstrapValidator} validator The validator plugin instance
  790. * @param {jQuery} $field Field element
  791. * @param {Object} options Can consist of the following keys:
  792. * - message: The invalid message
  793. * @returns {Boolean}
  794. */
  795. validate: function(validator, $field, options) {
  796. var value = $field.val();
  797. if (value == '') {
  798. return true;
  799. }
  800. return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(value);
  801. }
  802. };
  803. }(window.jQuery));
  804. ;(function($) {
  805. $.fn.bootstrapValidator.validators.identical = {
  806. /**
  807. * Check if input value equals to value of particular one
  808. *
  809. * @param {BootstrapValidator} validator The validator plugin instance
  810. * @param {jQuery} $field Field element
  811. * @param {Object} options Consists of the following key:
  812. * - field: The name of field that will be used to compare with current one
  813. * @returns {Boolean}
  814. */
  815. validate: function(validator, $field, options) {
  816. var value = $field.val();
  817. if (value == '') {
  818. return true;
  819. }
  820. var compareWith = validator.getFieldElements(options.field);
  821. if (compareWith == null) {
  822. return true;
  823. }
  824. if (value == compareWith.val()) {
  825. validator.updateStatus(compareWith, validator.STATUS_VALID, 'identical');
  826. return true;
  827. } else {
  828. return false;
  829. }
  830. }
  831. };
  832. }(window.jQuery));
  833. ;(function($) {
  834. $.fn.bootstrapValidator.validators.lessThan = {
  835. /**
  836. * Return true if the input value is less than or equal to given number
  837. *
  838. * @param {BootstrapValidator} validator The validator plugin instance
  839. * @param {jQuery} $field Field element
  840. * @param {Object} options Can consist of the following keys:
  841. * - value: The number used to compare to
  842. * - inclusive [optional]: Can be true or false. Default is true
  843. * - message: The invalid message
  844. * @returns {Boolean}
  845. */
  846. validate: function(validator, $field, options) {
  847. var value = $field.val();
  848. if (value == '') {
  849. return true;
  850. }
  851. value = parseFloat(value);
  852. return (options.inclusive === true) ? (value < options.value) : (value <= options.value);
  853. }
  854. };
  855. }(window.jQuery));
  856. ;(function($) {
  857. $.fn.bootstrapValidator.validators.notEmpty = {
  858. /**
  859. * Check if input value is empty or not
  860. *
  861. * @param {BootstrapValidator} validator The validator plugin instance
  862. * @param {jQuery} $field Field element
  863. * @param {Object} options
  864. * @returns {Boolean}
  865. */
  866. validate: function(validator, $field, options) {
  867. var type = $field.attr('type');
  868. if ('radio' == type || 'checkbox' == type) {
  869. return validator
  870. .getFieldElements($field.attr('name'))
  871. .filter(':checked')
  872. .length > 0;
  873. }
  874. return $.trim($field.val()) != '';
  875. }
  876. };
  877. }(window.jQuery));
  878. ;(function($) {
  879. $.fn.bootstrapValidator.validators.regexp = {
  880. /**
  881. * Check if the element value matches given regular expression
  882. *
  883. * @param {BootstrapValidator} validator The validator plugin instance
  884. * @param {jQuery} $field Field element
  885. * @param {Object} options Consists of the following key:
  886. * - regexp: The regular expression you need to check
  887. * @returns {Boolean}
  888. */
  889. validate: function(validator, $field, options) {
  890. var value = $field.val();
  891. if (value == '') {
  892. return true;
  893. }
  894. return options.regexp.test(value);
  895. }
  896. };
  897. }(window.jQuery));
  898. ;(function($) {
  899. $.fn.bootstrapValidator.validators.remote = {
  900. /**
  901. * Request a remote server to check the input value
  902. *
  903. * @param {BootstrapValidator} validator Plugin instance
  904. * @param {jQuery} $field Field element
  905. * @param {Object} options Can consist of the following keys:
  906. * - url
  907. * - data [optional]: By default, it will take the value
  908. * {
  909. * <fieldName>: <fieldValue>
  910. * }
  911. * - message: The invalid message
  912. * @returns {Boolean|Deferred}
  913. */
  914. validate: function(validator, $field, options) {
  915. var value = $field.val();
  916. if (value == '') {
  917. return true;
  918. }
  919. var name = $field.attr('name'), data = options.data;
  920. if (data == null) {
  921. data = {};
  922. }
  923. // Support dynamic data
  924. if ('function' == typeof data) {
  925. data = data.call(this, validator);
  926. }
  927. data[name] = value;
  928. var dfd = new $.Deferred();
  929. var xhr = $.ajax({
  930. type: 'POST',
  931. url: options.url,
  932. dataType: 'json',
  933. data: data
  934. });
  935. xhr.then(function(response) {
  936. dfd.resolve(response.valid === true || response.valid === 'true', 'remote');
  937. });
  938. dfd.fail(function() {
  939. xhr.abort();
  940. });
  941. return dfd;
  942. }
  943. };
  944. }(window.jQuery));
  945. ;(function($) {
  946. $.fn.bootstrapValidator.validators.stringLength = {
  947. /**
  948. * Check if the length of element value is less or more than given number
  949. *
  950. * @param {BootstrapValidator} validator The validator plugin instance
  951. * @param {jQuery} $field Field element
  952. * @param {Object} options Consists of following keys:
  953. * - min
  954. * - max
  955. * At least one of two keys is required
  956. * @returns {Boolean}
  957. */
  958. validate: function(validator, $field, options) {
  959. var value = $field.val();
  960. if (value == '') {
  961. return true;
  962. }
  963. var length = $.trim(value).length;
  964. if ((options.min && length < options.min) || (options.max && length > options.max)) {
  965. return false;
  966. }
  967. return true;
  968. }
  969. };
  970. }(window.jQuery));
  971. ;(function($) {
  972. $.fn.bootstrapValidator.validators.uri = {
  973. /**
  974. * Return true if the input value is a valid URL
  975. *
  976. * @param {BootstrapValidator} validator The validator plugin instance
  977. * @param {jQuery} $field Field element
  978. * @param {Object} options
  979. * @returns {Boolean}
  980. */
  981. validate: function(validator, $field, options) {
  982. var value = $field.val();
  983. if (value == '') {
  984. return true;
  985. }
  986. // Credit to https://gist.github.com/dperini/729294
  987. //
  988. // Regular Expression for URL validation
  989. //
  990. // Author: Diego Perini
  991. // Updated: 2010/12/05
  992. //
  993. // the regular expression composed & commented
  994. // could be easily tweaked for RFC compliance,
  995. // it was expressly modified to fit & satisfy
  996. // these test for an URL shortener:
  997. //
  998. // http://mathiasbynens.be/demo/url-regex
  999. //
  1000. // Notes on possible differences from a standard/generic validation:
  1001. //
  1002. // - utf-8 char class take in consideration the full Unicode range
  1003. // - TLDs have been made mandatory so single names like "localhost" fails
  1004. // - protocols have been restricted to ftp, http and https only as requested
  1005. //
  1006. // Changes:
  1007. //
  1008. // - IP address dotted notation validation, range: 1.0.0.0 - 223.255.255.255
  1009. // first and last IP address of each class is considered invalid
  1010. // (since they are broadcast/network addresses)
  1011. //
  1012. // - Added exclusion of private, reserved and/or local networks ranges
  1013. //
  1014. // Compressed one-line versions:
  1015. //
  1016. // Javascript version
  1017. //
  1018. // /^(?:(?: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
  1019. //
  1020. // PHP version
  1021. //
  1022. // _^(?:(?: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
  1023. var urlExp = new RegExp(
  1024. "^" +
  1025. // protocol identifier
  1026. "(?:(?:https?|ftp)://)" +
  1027. // user:pass authentication
  1028. "(?:\\S+(?::\\S*)?@)?" +
  1029. "(?:" +
  1030. // IP address exclusion
  1031. // private & local networks
  1032. "(?!10(?:\\.\\d{1,3}){3})" +
  1033. "(?!127(?:\\.\\d{1,3}){3})" +
  1034. "(?!169\\.254(?:\\.\\d{1,3}){2})" +
  1035. "(?!192\\.168(?:\\.\\d{1,3}){2})" +
  1036. "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" +
  1037. // IP address dotted notation octets
  1038. // excludes loopback network 0.0.0.0
  1039. // excludes reserved space >= 224.0.0.0
  1040. // excludes network & broacast addresses
  1041. // (first & last IP address of each class)
  1042. "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
  1043. "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
  1044. "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
  1045. "|" +
  1046. // host name
  1047. "(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)" +
  1048. // domain name
  1049. "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*" +
  1050. // TLD identifier
  1051. "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" +
  1052. ")" +
  1053. // port number
  1054. "(?::\\d{2,5})?" +
  1055. // resource path
  1056. "(?:/[^\\s]*)?" +
  1057. "$", "i"
  1058. );
  1059. return urlExp.test(value);
  1060. }
  1061. };
  1062. }(window.jQuery));
  1063. ;(function($) {
  1064. $.fn.bootstrapValidator.validators.zipCode = {
  1065. /**
  1066. * Return true if and only if the input value is a valid country zip code
  1067. *
  1068. * @param {BootstrapValidator} validator The validator plugin instance
  1069. * @param {jQuery} $field Field element
  1070. * @param {Object} options Consist of key:
  1071. * - country: The ISO 3166 country code
  1072. *
  1073. * Currently it supports the following countries:
  1074. * - US (United State)
  1075. * - DK (Denmark)
  1076. * - SE (Sweden)
  1077. *
  1078. * @returns {Boolean}
  1079. */
  1080. validate: function(validateInstance, $field, options) {
  1081. var value = $field.val();
  1082. if (value == '' || !options.country) {
  1083. return true;
  1084. }
  1085. switch (options.country.toUpperCase()) {
  1086. case 'DK':
  1087. return /^(DK(-|\s)?)?\d{4}$/i.test(value);
  1088. case 'SE':
  1089. return /^(S-)?\d{3}\s?\d{2}$/i.test(value);
  1090. case 'US':
  1091. default:
  1092. return /^\d{5}([\-]\d{4})?$/.test(value);
  1093. }
  1094. }
  1095. };
  1096. }(window.jQuery));