bootstrapValidator.js 46 KB

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