bootstrapValidator.js 43 KB

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