bootstrapValidator.js 42 KB

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