bootstrapValidator.js 33 KB

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