bootstrapValidator.js 47 KB

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