bootstrapValidator.js 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198
  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.2-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. var field, $field, type;
  409. for (field in this.options.fields) {
  410. this.dfds[field] = {};
  411. this.results[field] = {};
  412. $field = this.getFieldElements(field);
  413. // Mark field as not validated yet
  414. this.updateStatus($field, this.STATUS_NOT_VALIDATED, null);
  415. if (resetFormData) {
  416. type = $field.attr('type');
  417. ('radio' == type || 'checkbox' == type) ? $field.removeAttr('checked').removeAttr('selected') : $field.val('');
  418. }
  419. }
  420. this.invalidField = null;
  421. this.$submitButton = null;
  422. // Enable submit buttons
  423. this._disableSubmitButtons(false);
  424. return this;
  425. },
  426. /**
  427. * Enable/Disable all validators to given field
  428. *
  429. * @param {String} field The field name
  430. * @param {Boolean} enabled Enable/Disable field validators
  431. * @return {BootstrapValidator}
  432. */
  433. enableFieldValidators: function(field, enabled) {
  434. this.options.fields[field]['enabled'] = enabled;
  435. this.updateStatus(field, this.STATUS_NOT_VALIDATED, null);
  436. return this;
  437. }
  438. };
  439. // Plugin definition
  440. $.fn.bootstrapValidator = function(options) {
  441. return this.each(function() {
  442. var $this = $(this), data = $this.data('bootstrapValidator');
  443. if (!data) {
  444. $this.data('bootstrapValidator', (data = new BootstrapValidator(this, options)));
  445. }
  446. if ('string' == typeof options) {
  447. data[options]();
  448. }
  449. });
  450. };
  451. // Available validators
  452. $.fn.bootstrapValidator.validators = {};
  453. $.fn.bootstrapValidator.Constructor = BootstrapValidator;
  454. }(window.jQuery));
  455. ;(function($) {
  456. $.fn.bootstrapValidator.validators.between = {
  457. /**
  458. * Return true if the input value is between (strictly or not) two given numbers
  459. *
  460. * @param {BootstrapValidator} validator The validator plugin instance
  461. * @param {jQuery} $field Field element
  462. * @param {Object} options Can consist of the following keys:
  463. * - min
  464. * - max
  465. * - inclusive [optional]: Can be true or false. Default is true
  466. * - message: The invalid message
  467. * @returns {Boolean}
  468. */
  469. validate: function(validator, $field, options) {
  470. var value = $field.val();
  471. if (value == '') {
  472. return true;
  473. }
  474. value = parseFloat(value);
  475. return (options.inclusive === true)
  476. ? (value > options.min && value < options.max)
  477. : (value >= options.min && value <= options.max);
  478. }
  479. };
  480. }(window.jQuery));
  481. ;(function($) {
  482. $.fn.bootstrapValidator.validators.callback = {
  483. /**
  484. * Return result from the callback method
  485. *
  486. * @param {BootstrapValidator} validator The validator plugin instance
  487. * @param {jQuery} $field Field element
  488. * @param {Object} options Can consist of the following keys:
  489. * - callback: The callback method that passes 2 parameters:
  490. * callback: function(fieldValue, validator) {
  491. * // fieldValue is the value of field
  492. * // validator is instance of BootstrapValidator
  493. * }
  494. * - message: The invalid message
  495. * @returns {Boolean|Deferred}
  496. */
  497. validate: function(validator, $field, options) {
  498. var value = $field.val();
  499. if (options.callback && 'function' == typeof options.callback) {
  500. var dfd = new $.Deferred();
  501. dfd.resolve(options.callback.call(this, value, validator), 'callback');
  502. return dfd;
  503. }
  504. return true;
  505. }
  506. };
  507. }(window.jQuery));
  508. ;(function($) {
  509. $.fn.bootstrapValidator.validators.choice = {
  510. /**
  511. * Check if the number of checked boxes are less or more than a given number
  512. *
  513. * @param {BootstrapValidator} validator The validator plugin instance
  514. * @param {jQuery} $field Field element
  515. * @param {Object} options Consists of following keys:
  516. * - min
  517. * - max
  518. * At least one of two keys is required
  519. * @returns {Boolean}
  520. */
  521. validate: function(validator, $field, options) {
  522. var numChoices = validator
  523. .getFieldElements($field.attr('name'))
  524. .filter(':checked')
  525. .length;
  526. if ((options.min && numChoices < options.min) || (options.max && numChoices > options.max)) {
  527. return false;
  528. }
  529. return true;
  530. }
  531. };
  532. }(window.jQuery));
  533. ;(function($) {
  534. $.fn.bootstrapValidator.validators.creditCard = {
  535. /**
  536. * Return true if the input value is valid credit card number
  537. * Based on https://gist.github.com/DiegoSalazar/4075533
  538. *
  539. * @param {BootstrapValidator} validator The validator plugin instance
  540. * @param {jQuery} $field Field element
  541. * @param {Object} options Can consist of the following key:
  542. * - message: The invalid message
  543. * @returns {Boolean}
  544. */
  545. validate: function(validator, $field, options) {
  546. var value = $field.val();
  547. if (value == '') {
  548. return true;
  549. }
  550. // Accept only digits, dashes or spaces
  551. if (/[^0-9-\s]+/.test(value)) {
  552. return false;
  553. }
  554. // The Luhn Algorithm
  555. // http://en.wikipedia.org/wiki/Luhn
  556. value = value.replace(/\D/g, '');
  557. var check = 0, digit = 0, even = false, length = value.length;
  558. for (var n = length - 1; n >= 0; n--) {
  559. digit = parseInt(value.charAt(n), 10);
  560. if (even) {
  561. if ((digit *= 2) > 9) {
  562. digit -= 9;
  563. }
  564. }
  565. check += digit;
  566. even = !even;
  567. }
  568. return (check % 10) == 0;
  569. }
  570. };
  571. }(window.jQuery));
  572. ;(function($) {
  573. $.fn.bootstrapValidator.validators.date = {
  574. /**
  575. * Return true if the input value is valid date
  576. *
  577. * @param {BootstrapValidator} validator The validator plugin instance
  578. * @param {jQuery} $field Field element
  579. * @param {Object} options Can consist of the following keys:
  580. * - format: The date format. Default is MM/DD/YYYY
  581. * Support the following formats:
  582. * YYYY/DD/MM
  583. * YYYY/DD/MM h:m A
  584. * YYYY/MM/DD
  585. * YYYY/MM/DD h:m A
  586. *
  587. * YYYY-DD-MM
  588. * YYYY-DD-MM h:m A
  589. * YYYY-MM-DD
  590. * YYYY-MM-DD h:m A
  591. *
  592. * MM/DD/YYYY
  593. * MM/DD/YYYY h:m A
  594. * DD/MM/YYYY
  595. * DD/MM/YYYY h:m A
  596. *
  597. * MM-DD-YYYY
  598. * MM-DD-YYYY h:m A
  599. * DD-MM-YYYY
  600. * DD-MM-YYYY h:m A
  601. * - message: The invalid message
  602. * @returns {Boolean}
  603. */
  604. validate: function(validator, $field, options) {
  605. var value = $field.val();
  606. if (value == '') {
  607. return true;
  608. }
  609. // Determine the separator
  610. options.format = options.format || 'MM/DD/YYYY';
  611. var separator = (options.format.indexOf('/') != -1)
  612. ? '/'
  613. : ((options.format.indexOf('-') != -1) ? '-' : null);
  614. if (separator == null) {
  615. return false;
  616. }
  617. var month, day, year, minutes = null, hours = null, matches;
  618. switch (true) {
  619. case (separator == '/' && (matches = value.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})$/i)) && options.format == 'YYYY/DD/MM'):
  620. case (separator == '-' && (matches = value.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/i)) && options.format == 'YYYY-DD-MM'):
  621. year = matches[1]; day = matches[2]; month = matches[3];
  622. break;
  623. case (separator == '/' && (matches = value.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/i)) && options.format == 'DD/MM/YYYY'):
  624. case (separator == '-' && (matches = value.match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/i)) && options.format == 'DD-MM-YYYY'):
  625. day = matches[1]; month = matches[2]; year = matches[3];
  626. break;
  627. case (separator == '/' && (matches = value.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})$/i)) && options.format == 'YYYY/MM/DD'):
  628. case (separator == '-' && (matches = value.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/i)) && options.format == 'YYYY-MM-DD'):
  629. year = matches[1]; month = matches[2]; day = matches[3];
  630. break;
  631. case (separator == '/' && (matches = value.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/i)) && options.format == 'MM/DD/YYYY'):
  632. case (separator == '-' && (matches = value.match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/i)) && options.format == 'MM-DD-YYYY'):
  633. month = matches[1]; day = matches[2]; year = matches[3];
  634. break;
  635. 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'):
  636. 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'):
  637. year = matches[1]; day = matches[2]; month = matches[3]; hours = matches[4]; minutes = matches[5];
  638. break;
  639. 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'):
  640. 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'):
  641. day = matches[1]; month = matches[2]; year = matches[3]; hours = matches[4]; minutes = matches[5];
  642. break;
  643. 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'):
  644. 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'):
  645. year = matches[1]; month = matches[2]; day = matches[3]; hours = matches[4]; minutes = matches[5];
  646. break;
  647. 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'):
  648. 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'):
  649. month = matches[1]; day = matches[2]; year = matches[3]; hours = matches[4]; minutes = matches[5];
  650. break;
  651. default:
  652. return false;
  653. }
  654. // Validate hours and minutes
  655. if (hours && minutes) {
  656. hours = parseInt(hours, 10);
  657. minutes = parseInt(minutes, 10);
  658. if (hours < 1 || hours > 12 || minutes < 0 || minutes > 59) {
  659. return false;
  660. }
  661. }
  662. // Validate day, month, and year
  663. day = parseInt(day, 10);
  664. month = parseInt(month, 10);
  665. year = parseInt(year, 10);
  666. if (year < 1000 || year > 9999 || month == 0 || month > 12) {
  667. return false;
  668. }
  669. var numDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  670. // Update the number of days in Feb of leap year
  671. if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
  672. numDays[1] = 29;
  673. }
  674. // Check the day
  675. return (day > 0 && day <= numDays[month - 1]);
  676. }
  677. };
  678. }(window.jQuery));
  679. ;(function($) {
  680. $.fn.bootstrapValidator.validators.different = {
  681. /**
  682. * Return true if the input value is different with given field's value
  683. *
  684. * @param {BootstrapValidator} validator The validator plugin instance
  685. * @param {jQuery} $field Field element
  686. * @param {Object} options Consists of the following key:
  687. * - field: The name of field that will be used to compare with current one
  688. * @returns {Boolean}
  689. */
  690. validate: function(validator, $field, options) {
  691. var value = $field.val();
  692. if (value == '') {
  693. return true;
  694. }
  695. var compareWith = validator.getFieldElements(options.field);
  696. if (compareWith == null) {
  697. return true;
  698. }
  699. if (value != compareWith.val()) {
  700. validator.updateStatus(compareWith, validator.STATUS_VALID, 'different');
  701. return true;
  702. } else {
  703. return false;
  704. }
  705. }
  706. };
  707. }(window.jQuery));
  708. ;(function($) {
  709. $.fn.bootstrapValidator.validators.digits = {
  710. /**
  711. * Return true if the input value contains digits only
  712. *
  713. * @param {BootstrapValidator} validator Validate plugin instance
  714. * @param {jQuery} $field Field element
  715. * @param {Object} options
  716. * @returns {Boolean}
  717. */
  718. validate: function(validator, $field, options) {
  719. var value = $field.val();
  720. if (value == '') {
  721. return true;
  722. }
  723. return /^\d+$/.test(value);
  724. }
  725. }
  726. }(window.jQuery));
  727. ;(function($) {
  728. $.fn.bootstrapValidator.validators.emailAddress = {
  729. /**
  730. * Return true if and only if the input value is a valid email address
  731. *
  732. * @param {BootstrapValidator} validator Validate plugin instance
  733. * @param {jQuery} $field Field element
  734. * @param {Object} options
  735. * @returns {Boolean}
  736. */
  737. validate: function(validator, $field, options) {
  738. var value = $field.val();
  739. if (value == '') {
  740. return true;
  741. }
  742. // Email address regular expression
  743. // http://stackoverflow.com/questions/46155/validate-email-address-in-javascript
  744. 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,}))$/;
  745. return emailRegExp.test(value);
  746. }
  747. }
  748. }(window.jQuery));
  749. ;(function($) {
  750. $.fn.bootstrapValidator.validators.greaterThan = {
  751. /**
  752. * Return true if the input value is greater than or equals to given number
  753. *
  754. * @param {BootstrapValidator} validator Validate plugin instance
  755. * @param {jQuery} $field Field element
  756. * @param {Object} options Can consist of the following keys:
  757. * - value: The number used to compare to
  758. * - inclusive [optional]: Can be true or false. Default is true
  759. * - message: The invalid message
  760. * @returns {Boolean}
  761. */
  762. validate: function(validator, $field, options) {
  763. var value = $field.val();
  764. if (value == '') {
  765. return true;
  766. }
  767. value = parseFloat(value);
  768. return (options.inclusive === true) ? (value > options.value) : (value >= options.value);
  769. }
  770. }
  771. }(window.jQuery));
  772. ;(function($) {
  773. $.fn.bootstrapValidator.validators.hexColor = {
  774. /**
  775. * Return true if the input value is a valid hex color
  776. *
  777. * @param {BootstrapValidator} validator The validator plugin instance
  778. * @param {jQuery} $field Field element
  779. * @param {Object} options Can consist of the following keys:
  780. * - message: The invalid message
  781. * @returns {Boolean}
  782. */
  783. validate: function(validator, $field, options) {
  784. var value = $field.val();
  785. if (value == '') {
  786. return true;
  787. }
  788. return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(value);
  789. }
  790. };
  791. }(window.jQuery));
  792. ;(function($) {
  793. $.fn.bootstrapValidator.validators.identical = {
  794. /**
  795. * Check if input value equals to value of particular one
  796. *
  797. * @param {BootstrapValidator} validator The validator plugin instance
  798. * @param {jQuery} $field Field element
  799. * @param {Object} options Consists of the following key:
  800. * - field: The name of field that will be used to compare with current one
  801. * @returns {Boolean}
  802. */
  803. validate: function(validator, $field, options) {
  804. var value = $field.val();
  805. if (value == '') {
  806. return true;
  807. }
  808. var compareWith = validator.getFieldElements(options.field);
  809. if (compareWith == null) {
  810. return true;
  811. }
  812. if (value == compareWith.val()) {
  813. validator.updateStatus(compareWith, validator.STATUS_VALID, 'identical');
  814. return true;
  815. } else {
  816. return false;
  817. }
  818. }
  819. };
  820. }(window.jQuery));
  821. ;(function($) {
  822. $.fn.bootstrapValidator.validators.lessThan = {
  823. /**
  824. * Return true if the input value is less than or equal to given number
  825. *
  826. * @param {BootstrapValidator} validator The validator plugin instance
  827. * @param {jQuery} $field Field element
  828. * @param {Object} options Can consist of the following keys:
  829. * - value: The number used to compare to
  830. * - inclusive [optional]: Can be true or false. Default is true
  831. * - message: The invalid message
  832. * @returns {Boolean}
  833. */
  834. validate: function(validator, $field, options) {
  835. var value = $field.val();
  836. if (value == '') {
  837. return true;
  838. }
  839. value = parseFloat(value);
  840. return (options.inclusive === true) ? (value < options.value) : (value <= options.value);
  841. }
  842. };
  843. }(window.jQuery));
  844. ;(function($) {
  845. $.fn.bootstrapValidator.validators.notEmpty = {
  846. /**
  847. * Check if input value is empty or not
  848. *
  849. * @param {BootstrapValidator} validator The validator plugin instance
  850. * @param {jQuery} $field Field element
  851. * @param {Object} options
  852. * @returns {Boolean}
  853. */
  854. validate: function(validator, $field, options) {
  855. var type = $field.attr('type');
  856. if ('radio' == type || 'checkbox' == type) {
  857. return validator
  858. .getFieldElements($field.attr('name'))
  859. .filter(':checked')
  860. .length > 0;
  861. }
  862. return $.trim($field.val()) != '';
  863. }
  864. };
  865. }(window.jQuery));
  866. ;(function($) {
  867. $.fn.bootstrapValidator.validators.regexp = {
  868. /**
  869. * Check if the element value matches given regular expression
  870. *
  871. * @param {BootstrapValidator} validator The validator plugin instance
  872. * @param {jQuery} $field Field element
  873. * @param {Object} options Consists of the following key:
  874. * - regexp: The regular expression you need to check
  875. * @returns {Boolean}
  876. */
  877. validate: function(validator, $field, options) {
  878. var value = $field.val();
  879. if (value == '') {
  880. return true;
  881. }
  882. return options.regexp.test(value);
  883. }
  884. };
  885. }(window.jQuery));
  886. ;(function($) {
  887. $.fn.bootstrapValidator.validators.remote = {
  888. /**
  889. * Request a remote server to check the input value
  890. *
  891. * @param {BootstrapValidator} validator Plugin instance
  892. * @param {jQuery} $field Field element
  893. * @param {Object} options Can consist of the following keys:
  894. * - url
  895. * - data [optional]: By default, it will take the value
  896. * {
  897. * <fieldName>: <fieldValue>
  898. * }
  899. * - message: The invalid message
  900. * @returns {Boolean|Deferred}
  901. */
  902. validate: function(validator, $field, options) {
  903. var value = $field.val();
  904. if (value == '') {
  905. return true;
  906. }
  907. var name = $field.attr('name'), data = options.data;
  908. if (data == null) {
  909. data = {};
  910. }
  911. // Support dynamic data
  912. if ('function' == typeof data) {
  913. data = data.call(this, validator);
  914. }
  915. data[name] = value;
  916. var dfd = new $.Deferred();
  917. var xhr = $.ajax({
  918. type: 'POST',
  919. url: options.url,
  920. dataType: 'json',
  921. data: data
  922. });
  923. xhr.then(function(response) {
  924. dfd.resolve(response.valid === true || response.valid === 'true', 'remote');
  925. });
  926. dfd.fail(function() {
  927. xhr.abort();
  928. });
  929. return dfd;
  930. }
  931. };
  932. }(window.jQuery));
  933. ;(function($) {
  934. $.fn.bootstrapValidator.validators.stringLength = {
  935. /**
  936. * Check if the length of element value is less or more than given number
  937. *
  938. * @param {BootstrapValidator} validator The validator plugin instance
  939. * @param {jQuery} $field Field element
  940. * @param {Object} options Consists of following keys:
  941. * - min
  942. * - max
  943. * At least one of two keys is required
  944. * @returns {Boolean}
  945. */
  946. validate: function(validator, $field, options) {
  947. var value = $field.val();
  948. if (value == '') {
  949. return true;
  950. }
  951. var length = $.trim(value).length;
  952. if ((options.min && length < options.min) || (options.max && length > options.max)) {
  953. return false;
  954. }
  955. return true;
  956. }
  957. };
  958. }(window.jQuery));
  959. ;(function($) {
  960. $.fn.bootstrapValidator.validators.uri = {
  961. /**
  962. * Return true if the input value is a valid URL
  963. *
  964. * @param {BootstrapValidator} validator The validator plugin instance
  965. * @param {jQuery} $field Field element
  966. * @param {Object} options
  967. * @returns {Boolean}
  968. */
  969. validate: function(validator, $field, options) {
  970. var value = $field.val();
  971. if (value == '') {
  972. return true;
  973. }
  974. // Credit to https://gist.github.com/dperini/729294
  975. //
  976. // Regular Expression for URL validation
  977. //
  978. // Author: Diego Perini
  979. // Updated: 2010/12/05
  980. //
  981. // the regular expression composed & commented
  982. // could be easily tweaked for RFC compliance,
  983. // it was expressly modified to fit & satisfy
  984. // these test for an URL shortener:
  985. //
  986. // http://mathiasbynens.be/demo/url-regex
  987. //
  988. // Notes on possible differences from a standard/generic validation:
  989. //
  990. // - utf-8 char class take in consideration the full Unicode range
  991. // - TLDs have been made mandatory so single names like "localhost" fails
  992. // - protocols have been restricted to ftp, http and https only as requested
  993. //
  994. // Changes:
  995. //
  996. // - IP address dotted notation validation, range: 1.0.0.0 - 223.255.255.255
  997. // first and last IP address of each class is considered invalid
  998. // (since they are broadcast/network addresses)
  999. //
  1000. // - Added exclusion of private, reserved and/or local networks ranges
  1001. //
  1002. // Compressed one-line versions:
  1003. //
  1004. // Javascript version
  1005. //
  1006. // /^(?:(?: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
  1007. //
  1008. // PHP version
  1009. //
  1010. // _^(?:(?: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
  1011. var urlExp = new RegExp(
  1012. "^" +
  1013. // protocol identifier
  1014. "(?:(?:https?|ftp)://)" +
  1015. // user:pass authentication
  1016. "(?:\\S+(?::\\S*)?@)?" +
  1017. "(?:" +
  1018. // IP address exclusion
  1019. // private & local networks
  1020. "(?!10(?:\\.\\d{1,3}){3})" +
  1021. "(?!127(?:\\.\\d{1,3}){3})" +
  1022. "(?!169\\.254(?:\\.\\d{1,3}){2})" +
  1023. "(?!192\\.168(?:\\.\\d{1,3}){2})" +
  1024. "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" +
  1025. // IP address dotted notation octets
  1026. // excludes loopback network 0.0.0.0
  1027. // excludes reserved space >= 224.0.0.0
  1028. // excludes network & broacast addresses
  1029. // (first & last IP address of each class)
  1030. "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
  1031. "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
  1032. "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
  1033. "|" +
  1034. // host name
  1035. "(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)" +
  1036. // domain name
  1037. "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*" +
  1038. // TLD identifier
  1039. "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" +
  1040. ")" +
  1041. // port number
  1042. "(?::\\d{2,5})?" +
  1043. // resource path
  1044. "(?:/[^\\s]*)?" +
  1045. "$", "i"
  1046. );
  1047. return urlExp.test(value);
  1048. }
  1049. };
  1050. }(window.jQuery));
  1051. ;(function($) {
  1052. $.fn.bootstrapValidator.validators.zipCode = {
  1053. /**
  1054. * Return true if and only if the input value is a valid country zip code
  1055. *
  1056. * @param {BootstrapValidator} validator The validator plugin instance
  1057. * @param {jQuery} $field Field element
  1058. * @param {Object} options Consist of key:
  1059. * - country: The ISO 3166 country code
  1060. *
  1061. * Currently it supports the following countries:
  1062. * - US (United State)
  1063. * - DK (Denmark)
  1064. * - SE (Sweden)
  1065. *
  1066. * @returns {Boolean}
  1067. */
  1068. validate: function(validateInstance, $field, options) {
  1069. var value = $field.val();
  1070. if (value == '' || !options.country) {
  1071. return true;
  1072. }
  1073. switch (options.country.toUpperCase()) {
  1074. case 'DK':
  1075. return /^(DK(-|\s)?)?\d{4}$/i.test(value);
  1076. case 'SE':
  1077. return /^(S-)?\d{3}\s?\d{2}$/i.test(value);
  1078. case 'US':
  1079. default:
  1080. return /^\d{5}([\-]\d{4})?$/.test(value);
  1081. }
  1082. }
  1083. };
  1084. }(window.jQuery));