bootstrapValidator.js 38 KB

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