bootstrapValidator.js 35 KB

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