bootstrapValidator.js 36 KB

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