bootstrapValidator.js 47 KB

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