bootstrapValidator.js 36 KB

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