bootstrapValidator.js 42 KB

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