bootstrapValidator.js 30 KB

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