bootstrapValidator.js 48 KB

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