bootstrapValidator.js 42 KB

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