bootstrapValidator.js 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  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._init();
  20. this.STATUS_NOT_VALIDATED = 'NOT_VALIDATED';
  21. this.STATUS_VALIDATING = 'VALIDATING';
  22. this.STATUS_INVALID = 'INVALID';
  23. this.STATUS_VALID = 'VALID';
  24. };
  25. // The default options
  26. BootstrapValidator.DEFAULT_OPTIONS = {
  27. // The form CSS class
  28. elementClass: 'bootstrap-validator-form',
  29. // Default invalid message
  30. message: 'This value is not valid',
  31. // Shows ok/error/loading icons based on the field validity.
  32. // This feature requires Bootstrap v3.1.0 or later (http://getbootstrap.com/css/#forms-control-validation).
  33. // Since Bootstrap doesn't provide any methods to know its version, this option cannot be on/off automatically.
  34. // In other word, to use this feature you have to upgrade your Bootstrap to v3.1.0 or later.
  35. //
  36. // Examples:
  37. // - Use Glyphicons icons:
  38. // feedbackIcons: {
  39. // valid: 'glyphicon glyphicon-ok',
  40. // invalid: 'glyphicon glyphicon-remove',
  41. // validating: 'glyphicon glyphicon-refresh'
  42. // }
  43. // - Use FontAwesome icons:
  44. // feedbackIcons: {
  45. // valid: 'fa fa-check',
  46. // invalid: 'fa fa-times',
  47. // validating: 'fa fa-refresh'
  48. // }
  49. feedbackIcons: null,
  50. // The submit buttons selector
  51. // These buttons will be disabled to prevent the valid form from multiple submissions
  52. submitButtons: 'button[type="submit"]',
  53. // The custom submit handler
  54. // It will prevent the form from the default submission
  55. //
  56. // submitHandler: function(validator, form) {
  57. // - validator is the BootstrapValidator instance
  58. // - form is the jQuery object present the current form
  59. // }
  60. submitHandler: null,
  61. // Live validating option
  62. // Can be one of 3 values:
  63. // - enabled: The plugin validates fields as soon as they are changed
  64. // - disabled: Disable the live validating. The error messages are only shown after the form is submitted
  65. // - submitted: The live validating is enabled after the form is submitted
  66. live: 'enabled',
  67. // Map the field name with validator rules
  68. fields: null
  69. };
  70. BootstrapValidator.prototype = {
  71. constructor: BootstrapValidator,
  72. /**
  73. * Init form
  74. */
  75. _init: function() {
  76. if (this.options.fields == null) {
  77. return;
  78. }
  79. var that = this;
  80. this.$form
  81. // Disable client side validation in HTML 5
  82. .attr('novalidate', 'novalidate')
  83. .addClass(this.options.elementClass)
  84. // Disable the default submission first
  85. .on('submit.bootstrapValidator', function(e) {
  86. e.preventDefault();
  87. that.validate();
  88. })
  89. .find(this.options.submitButtons)
  90. .on('click', function() {
  91. that.$submitButton = $(this);
  92. });
  93. for (var field in this.options.fields) {
  94. this._initField(field);
  95. }
  96. this._setLiveValidating();
  97. },
  98. /**
  99. * Init field
  100. *
  101. * @param {String} field The field name
  102. */
  103. _initField: function(field) {
  104. if (this.options.fields[field] == null || this.options.fields[field].validators == null) {
  105. return;
  106. }
  107. this.dfds[field] = {};
  108. this.results[field] = {};
  109. var fields = this.getFieldElements(field);
  110. // We don't need to validate non-existing fields
  111. if (fields == null) {
  112. delete this.options.fields[field];
  113. delete this.dfds[field];
  114. return;
  115. }
  116. // Create help block elements for showing the error messages
  117. var $field = $(fields[0]),
  118. $parent = $field.parents('.form-group'),
  119. $message = this._getMessageContainer($field);
  120. $field.data('bootstrapValidator.messageContainer', $message);
  121. for (var validatorName in this.options.fields[field].validators) {
  122. if (!$.fn.bootstrapValidator.validators[validatorName]) {
  123. delete this.options.fields[field].validators[validatorName];
  124. continue;
  125. }
  126. this.results[field][validatorName] = this.STATUS_NOT_VALIDATED;
  127. $('<small/>')
  128. .css('display', 'none')
  129. .attr('data-bs-validator', validatorName)
  130. .html(this.options.fields[field].validators[validatorName].message || this.options.message)
  131. .addClass('help-block')
  132. .appendTo($message);
  133. }
  134. // Prepare the feedback icons
  135. // Available from Bootstrap 3.1 (http://getbootstrap.com/css/#forms-control-validation)
  136. if (this.options.feedbackIcons) {
  137. $parent.addClass('has-feedback');
  138. var $icon = $('<i/>').css('display', 'none').addClass('form-control-feedback').insertAfter($(fields[fields.length - 1]));
  139. // The feedback icon does not render correctly if there is no label
  140. // https://github.com/twbs/bootstrap/issues/12873
  141. if ($parent.find('label').length == 0) {
  142. $icon.css('top', 0);
  143. }
  144. }
  145. if (this.options.fields[field]['enabled'] == null) {
  146. this.options.fields[field]['enabled'] = true;
  147. }
  148. // Whenever the user change the field value, mark it as not validated yet
  149. var that = this,
  150. type = fields.attr('type'),
  151. event = ('radio' == type || 'checkbox' == type || 'SELECT' == fields[0].tagName) ? 'change' : 'keyup';
  152. fields.on(event, function() {
  153. that.setNotValidated(field);
  154. });
  155. },
  156. /**
  157. * Get the element to place the error messages
  158. *
  159. * @param {jQuery} $field The field element
  160. * @returns {jQuery}
  161. */
  162. _getMessageContainer: function($field) {
  163. var $parent = $field.parent();
  164. if ($parent.hasClass('form-group')) {
  165. return $parent;
  166. }
  167. var cssClasses = $parent.attr('class');
  168. if (!cssClasses) {
  169. return this._getMessageContainer($parent);
  170. }
  171. cssClasses = cssClasses.split(' ');
  172. var n = cssClasses.length;
  173. for (var i = 0; i < n; i++) {
  174. if (/^col-(xs|sm|md|lg)-\d+$/.test(cssClasses[i]) || /^col-(xs|sm|md|lg)-offset-\d+$/.test(cssClasses[i])) {
  175. return $parent;
  176. }
  177. }
  178. return this._getMessageContainer($parent);
  179. },
  180. /**
  181. * Enable live validating
  182. */
  183. _setLiveValidating: function() {
  184. if ('enabled' == this.options.live) {
  185. var that = this;
  186. for (var field in this.options.fields) {
  187. (function(f) {
  188. var fields = that.getFieldElements(f);
  189. if (fields) {
  190. var type = fields.attr('type'),
  191. event = ('radio' == type || 'checkbox' == type || 'SELECT' == fields[0].tagName) ? 'change' : 'keyup';
  192. fields.on(event, function() {
  193. that.validateField(f);
  194. });
  195. }
  196. })(field);
  197. }
  198. }
  199. },
  200. /**
  201. * Disable/Enable submit buttons
  202. *
  203. * @param {Boolean} disabled
  204. */
  205. _disableSubmitButtons: function(disabled) {
  206. if (!disabled) {
  207. this.$form.find(this.options.submitButtons).removeAttr('disabled');
  208. } else if (this.options.live != 'disabled') {
  209. // Don't disable if the live validating mode is disabled
  210. this.$form.find(this.options.submitButtons).attr('disabled', 'disabled');
  211. }
  212. },
  213. /**
  214. * Called when all validations are completed
  215. */
  216. _submit: function() {
  217. if (!this.isValid()) {
  218. if ('submitted' == this.options.live) {
  219. this.options.live = 'enabled';
  220. this._setLiveValidating();
  221. }
  222. // Focus to the first invalid field
  223. if (this.invalidField) {
  224. this.getFieldElements(this.invalidField).focus();
  225. }
  226. return;
  227. }
  228. this._disableSubmitButtons(true);
  229. // Call the custom submission if enabled
  230. if (this.options.submitHandler && 'function' == typeof this.options.submitHandler) {
  231. this.options.submitHandler.call(this, this, this.$form, this.$submitButton);
  232. } else {
  233. // Submit form
  234. this.$form.off('submit.bootstrapValidator').submit();
  235. }
  236. },
  237. // --- Public methods ---
  238. /**
  239. * Retrieve the field elements by given name
  240. *
  241. * @param {String} field The field name
  242. * @returns {null|jQuery[]}
  243. */
  244. getFieldElements: function(field) {
  245. var fields = this.$form.find('[name="' + field + '"]');
  246. return (fields.length == 0) ? null : fields;
  247. },
  248. /**
  249. * Validate the form
  250. *
  251. * @return {BootstrapValidator}
  252. */
  253. validate: function() {
  254. if (!this.options.fields) {
  255. return this;
  256. }
  257. this._disableSubmitButtons(true);
  258. for (var field in this.options.fields) {
  259. this.validateField(field);
  260. }
  261. this._submit();
  262. return this;
  263. },
  264. /**
  265. * Validate given field
  266. *
  267. * @param {String} field The field name
  268. */
  269. validateField: function(field) {
  270. if (!this.options.fields[field]['enabled']) {
  271. return;
  272. }
  273. var that = this,
  274. fields = this.getFieldElements(field),
  275. $field = $(fields[0]),
  276. validators = this.options.fields[field].validators,
  277. validatorName,
  278. validateResult;
  279. // We don't need to validate disabled field
  280. if (fields.length == 1 && fields.is(':disabled')) {
  281. delete this.options.fields[field];
  282. delete this.dfds[field];
  283. return;
  284. }
  285. for (validatorName in validators) {
  286. if (this.dfds[field][validatorName]) {
  287. this.dfds[field][validatorName].reject();
  288. }
  289. // Don't validate field if it is already done
  290. if (this.results[field][validatorName] == this.STATUS_VALID || this.results[field][validatorName] == this.STATUS_INVALID) {
  291. continue;
  292. }
  293. this.results[field][validatorName] = this.STATUS_VALIDATING;
  294. validateResult = $.fn.bootstrapValidator.validators[validatorName].validate(this, $field, validators[validatorName]);
  295. if ('object' == typeof validateResult) {
  296. this.updateStatus($field, this.STATUS_VALIDATING, validatorName);
  297. this.dfds[field][validatorName] = validateResult;
  298. validateResult.done(function(isValid, v) {
  299. // v is validator name
  300. delete that.dfds[field][v];
  301. that.updateStatus($field, isValid ? that.STATUS_VALID : that.STATUS_INVALID, v);
  302. if (isValid && 'disabled' == that.options.live) {
  303. that._submit();
  304. }
  305. });
  306. } else if ('boolean' == typeof validateResult) {
  307. this.updateStatus($field, validateResult ? this.STATUS_VALID : this.STATUS_INVALID, validatorName);
  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 The validator name
  339. * @param {String} status The status
  340. * Can be STATUS_VALIDATING, STATUS_INVALID, STATUS_VALID
  341. * @return {BootstrapValidator}
  342. */
  343. updateStatus: function($field, status, validatorName) {
  344. var that = this,
  345. field = $field.attr('name'),
  346. $parent = $field.parents('.form-group'),
  347. $message = $field.data('bootstrapValidator.messageContainer'),
  348. $errors = $message.find('.help-block[data-bs-validator]');
  349. switch (status) {
  350. case this.STATUS_VALIDATING:
  351. this.results[field][validatorName] = this.STATUS_VALIDATING;
  352. this._disableSubmitButtons(true);
  353. $parent.removeClass('has-success').removeClass('has-error');
  354. // TODO: Show validating message
  355. $errors.filter('.help-block[data-bs-validator="' + validatorName + '"]').hide();
  356. if (this.options.feedbackIcons) {
  357. // Show validating icon
  358. $message.find('.form-control-feedback').removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).addClass(this.options.feedbackIcons.validating).show();
  359. }
  360. break;
  361. case this.STATUS_INVALID:
  362. this.results[field][validatorName] = this.STATUS_INVALID;
  363. this._disableSubmitButtons(true);
  364. // Add has-error class to parent element
  365. $parent.removeClass('has-success').addClass('has-error');
  366. $errors.filter('[data-bs-validator="' + validatorName + '"]').show();
  367. if (this.options.feedbackIcons) {
  368. // Show invalid icon
  369. $message.find('.form-control-feedback').removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.validating).addClass(this.options.feedbackIcons.invalid).show();
  370. }
  371. break;
  372. case this.STATUS_VALID:
  373. this.results[field][validatorName] = this.STATUS_VALID;
  374. // Hide error element
  375. $errors.filter('[data-bs-validator="' + validatorName + '"]').hide();
  376. // If the field is valid
  377. if ($errors.filter(function() {
  378. var display = $(this).css('display'), v = $(this).attr('data-bs-validator');
  379. return ('block' == display) || (that.results[field][v] != that.STATUS_VALID);
  380. }).length == 0
  381. ) {
  382. this._disableSubmitButtons(false);
  383. $parent.removeClass('has-error').addClass('has-success');
  384. // Show valid icon
  385. if (this.options.feedbackIcons) {
  386. $message.find('.form-control-feedback').removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).addClass(this.options.feedbackIcons.valid).show();
  387. }
  388. }
  389. break;
  390. default:
  391. break;
  392. }
  393. return this;
  394. },
  395. /**
  396. * Mark a field as not validated yet
  397. * The plugin doesn't re-validate a field if it is marked as valid.
  398. * In some cases, we need to force the plugin validate it again
  399. *
  400. * @param {String} field The field name
  401. * @returns {BootstrapValidator}
  402. */
  403. setNotValidated: function(field) {
  404. for (var v in this.options.fields[field].validators) {
  405. this.results[field][v] = this.STATUS_NOT_VALIDATED;
  406. }
  407. return this;
  408. },
  409. // Useful APIs which aren't used internally
  410. /**
  411. * Reset the form
  412. *
  413. * @param {Boolean} resetFormData Reset current form data
  414. * @return {BootstrapValidator}
  415. */
  416. resetForm: function(resetFormData) {
  417. for (var field in this.options.fields) {
  418. this.dfds[field] = {};
  419. this.results[field] = {};
  420. // Mark field as not validated yet
  421. this.setNotValidated(field);
  422. }
  423. this.invalidField = null;
  424. this.$submitButton = null;
  425. // Hide all error elements
  426. this.$form
  427. .find('.has-error').removeClass('has-error').end()
  428. .find('.has-success').removeClass('has-success').end()
  429. .find('.help-block[data-bs-validator]').hide();
  430. // Enable submit buttons
  431. this._disableSubmitButtons(false);
  432. // Hide all feedback icons
  433. if (this.options.feedbackIcons) {
  434. this.$form.find('.form-control-feedback').removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).hide();
  435. }
  436. if (resetFormData) {
  437. this.$form.get(0).reset();
  438. }
  439. return this;
  440. },
  441. /**
  442. * Enable/Disable all validators to given field
  443. *
  444. * @param {String} field The field name
  445. * @param {Boolean} enabled Enable/Disable field validators
  446. * @return {BootstrapValidator}
  447. */
  448. enableFieldValidators: function(field, enabled) {
  449. this.options.fields[field]['enabled'] = enabled;
  450. if (enabled) {
  451. this.setNotValidated(field);
  452. } else {
  453. var $field = this.getFieldElements(field),
  454. $message = $field.data('bootstrapValidator.messageContainer');
  455. $field.parents('.form-group').removeClass('has-success has-error');
  456. $message.find('.help-block[data-bs-validator]').hide();
  457. if (this.options.feedbackIcons) {
  458. $message.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, validator.STATUS_VALID, 'different');
  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, validator.STATUS_VALID, 'identical');
  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));