bootstrapValidator.js 31 KB

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