bootstrapValidator.js 46 KB

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