bootstrapValidator.js 44 KB

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