bootstrapValidator.js 38 KB

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