bootstrapvalidate.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. /**
  2. * BootstrapValidate v0.1.0 (http://github.com/nghuuphuoc/bootstrapvalidate)
  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. // Plugin definition
  12. $.fn.bootstrapValidate = function(options) {
  13. return this.each(function() {
  14. var $this = $(this), data = $this.data('bootstrapValidate');
  15. if (!data) {
  16. $this.data('bootstrapValidate', (data = new $.bootstrapValidator(this, options)));
  17. }
  18. });
  19. };
  20. $.bootstrapValidator = function(form, options) {
  21. this.$form = $(form);
  22. this.options = $.extend({}, $.bootstrapValidator.DEFAULT_OPTIONS, options);
  23. this.validate();
  24. this.xhrRequests = {};
  25. this.numPendingRequests = 0;
  26. };
  27. $.extend($.bootstrapValidator, {
  28. /**
  29. * The default options
  30. */
  31. DEFAULT_OPTIONS: {
  32. // Default invalid message
  33. message: 'This value is not valid',
  34. // Map the field name with validator rules
  35. fields: null,
  36. // CSS class of icons indicating that the field value is valid or not
  37. iconClass: {
  38. valid: 'icon-ok',
  39. invalid: 'icon-remove'
  40. }
  41. },
  42. // Available validators
  43. validator: {},
  44. prototype: {
  45. /**
  46. * Retrieve the form element
  47. * @returns {jQuery}
  48. */
  49. getForm: function() {
  50. return this.$form;
  51. },
  52. /**
  53. * Validate form
  54. */
  55. validate: function() {
  56. if (this.options.fields == null) {
  57. return;
  58. }
  59. for (var field in this.options.fields) {
  60. this.validateField(field);
  61. }
  62. },
  63. validateField: function(field) {
  64. if (this.options.fields[field] == null || this.options.fields[field].validator == null) {
  65. return;
  66. }
  67. var foundFields = this.$form.find('[name="' + field + '"]');
  68. if (foundFields.length == 0) {
  69. // Return if cannot find the field with given name
  70. return;
  71. }
  72. var that = this,
  73. fieldElement = $(foundFields[0]),
  74. type = $(fieldElement).attr('type'),
  75. event = ('checkbox' == type || 'radio' == type) ? 'change' : 'keyup';
  76. $(fieldElement)
  77. .on(event, function() {
  78. var validators = that.options.fields[field].validator;
  79. for (var validatorName in validators) {
  80. if (!$.bootstrapValidator.validator[validatorName]) {
  81. continue;
  82. }
  83. var isValid = $.bootstrapValidator.validator[validatorName].validate(that, fieldElement, validators[validatorName]);
  84. if (isValid == false) {
  85. that.showError(fieldElement, validatorName);
  86. break;
  87. } else if (isValid == true) {
  88. that.removeError(fieldElement);
  89. }
  90. }
  91. })
  92. .blur(function() {
  93. that.hideError(fieldElement);
  94. });
  95. },
  96. showError: function(fieldElement, validatorName) {
  97. var $fieldElement = $(fieldElement),
  98. field = $fieldElement.attr('name'),
  99. validator = this.options.fields[field].validator[validatorName],
  100. message = validator.message || this.options.message;
  101. if (!$fieldElement.data('bootstrapValidator.tooltip')) {
  102. var $a = $('<a/>').attr('href', '#')
  103. .attr('title', message)
  104. // Bootstrap tooltip options
  105. // see http://getbootstrap.com/javascript/#tooltips
  106. .attr('data-toggle', 'tooltip').attr('data-placement', 'right')
  107. .css('text-decoration', 'none')
  108. .css('position', 'absolute')
  109. .insertAfter(fieldElement);
  110. $('<i/>').addClass(this.options.iconClass.invalid).appendTo($a);
  111. $fieldElement.data('bootstrapValidator.tooltip', $a);
  112. $a.on('shown.bs.tooltip', function() {
  113. if (!$(this).data('bootstrapValidator.tooltip.calculated')) {
  114. $(this).data('bootstrapValidator.tooltip.calculated', true);
  115. var $parent = $(this).parent(),
  116. $tip = $(this).data('bs.tooltip').$tip,
  117. w = $parent.width(),
  118. h = $parent.height(),
  119. tipWidth = parseInt($tip.width()),
  120. tipHeight = parseInt($tip.height()),
  121. tipLeft = parseInt($tip.css('left')),
  122. tipTop = parseInt($tip.css('top'));
  123. $tip.css('left', tipLeft + w + 10)
  124. .css('top', tipTop - h + 5)
  125. .width(tipWidth);
  126. $(this).css('position', 'absolute')
  127. .css('left', tipLeft - $(this).width() + w + 5)
  128. .css('top', tipTop + tipHeight / 2 - $(this).height() / 2 - h + 5);
  129. }
  130. });
  131. }
  132. // Add has-error class to parent element
  133. $fieldElement.parents('.form-group').removeClass('has-success').addClass('has-error');
  134. var $tip = $fieldElement.data('bootstrapValidator.tooltip');
  135. $tip.find('i').attr('class', this.options.iconClass.invalid).end()
  136. .attr('title', message)
  137. .attr('data-original-title', message)
  138. .tooltip('show');
  139. },
  140. hideError: function(fieldElement) {
  141. if (tip = $(fieldElement).data('bootstrapValidator.tooltip')) {
  142. $(tip).tooltip('hide');
  143. }
  144. },
  145. removeError: function(fieldElement) {
  146. var $fieldElement = $(fieldElement);
  147. $fieldElement.parents('.form-group').removeClass('has-error').addClass('has-success');
  148. if (tip = $fieldElement.data('bootstrapValidator.tooltip')) {
  149. $(tip).find('i').attr('class', this.options.iconClass.valid);
  150. $(tip).tooltip('destroy');
  151. $(tip).remove();
  152. $fieldElement.removeData('bootstrapValidator.tooltip');
  153. }
  154. },
  155. startRequest: function(fieldElement, validatorName, xhr) {
  156. var field = $(fieldElement).attr('name');
  157. this.completeRequest(fieldElement, validatorName);
  158. if (this.numPendingRequests < 0) {
  159. this.numPendingRequests = 0;
  160. }
  161. this.numPendingRequests++;
  162. if (!this.xhrRequests[field]) {
  163. this.xhrRequests[field] = {};
  164. }
  165. this.xhrRequests[field][validatorName] = xhr;
  166. },
  167. completeRequest: function(fieldElement, validatorName) {
  168. var field = $(fieldElement).attr('name');
  169. if (!this.xhrRequests[field] || !this.xhrRequests[field][validatorName]) {
  170. return;
  171. }
  172. var xhr = this.xhrRequests[field][validatorName];
  173. this.numPendingRequests--;
  174. console.log('---abort---');
  175. xhr.abort();
  176. delete this.xhrRequests[field][validatorName];
  177. }
  178. }
  179. });
  180. }(window.jQuery));
  181. ;(function($) {
  182. $.extend($.bootstrapValidator.validator, {
  183. between: {
  184. /**
  185. * Return true if the input value is between (strictly or not) two given numbers
  186. *
  187. * @param {bootstrapValidator} validateInstance Validate plugin instance
  188. * @param {HTMLElement} element
  189. * @param {Object} options Can consist of the following keys:
  190. * - min
  191. * - max
  192. * - inclusive [optional]: Can be true or false. Default is true
  193. * - message: The invalid message
  194. * @returns {boolean}
  195. */
  196. validate: function(validateInstance, element, options) {
  197. var value = parseFloat($(element).val());
  198. return (options.inclusive === true)
  199. ? (value > options.min && value < options.max)
  200. : (value >= options.min && value <= options.max);
  201. }
  202. }
  203. });
  204. }(window.jQuery));
  205. ;(function($) {
  206. $.extend($.bootstrapValidator.validator, {
  207. digits: {
  208. /**
  209. * Return true if the input value contains digits only
  210. *
  211. * @param {bootstrapValidator} validateInstance Validate plugin instance
  212. * @param {HTMLElement} element
  213. * @param {Object} options
  214. * @returns {boolean}
  215. */
  216. validate: function(validateInstance, element, options) {
  217. return /^\d+$/.test($(element).val());
  218. }
  219. }
  220. });
  221. }(window.jQuery));
  222. ;(function($) {
  223. $.extend($.bootstrapValidator.validator, {
  224. emailAddress: {
  225. /**
  226. * Return true if and only if the input value is a valid email address
  227. *
  228. * @param {bootstrapValidator} validateInstance Validate plugin instance
  229. * @param {HTMLElement} element
  230. * @param {Object} options
  231. * @returns {boolean}
  232. */
  233. validate: function(validateInstance, element, options) {
  234. var value = $.trim($(element).val()),
  235. // Email address regular expression
  236. // http://stackoverflow.com/questions/46155/validate-email-address-in-javascript
  237. 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,}))$/;
  238. return emailRegExp.test(value);
  239. }
  240. }
  241. });
  242. }(window.jQuery));
  243. ;(function($) {
  244. $.extend($.bootstrapValidator.validator, {
  245. greaterThan: {
  246. /**
  247. * Return true if the input value is greater than or equals to given number
  248. *
  249. * @param {bootstrapValidator} validateInstance Validate plugin instance
  250. * @param {HTMLElement} element
  251. * @param {Object} options Can consist of the following keys:
  252. * - value: The number used to compare to
  253. * - inclusive [optional]: Can be true or false. Default is true
  254. * - message: The invalid message
  255. * @returns {boolean}
  256. */
  257. validate: function(validateInstance, element, options) {
  258. var value = parseFloat($(element).val());
  259. return (options.inclusive === true) ? (value > options.value) : (value >= options.value);
  260. }
  261. }
  262. });
  263. }(window.jQuery));
  264. ;(function($) {
  265. $.extend($.bootstrapValidator.validator, {
  266. hexColor: {
  267. /**
  268. * Return true if the input value is a valid hex color
  269. *
  270. * @param {bootstrapValidator} validateInstance Validate plugin instance
  271. * @param {HTMLElement} element
  272. * @param {Object} options Can consist of the following keys:
  273. * - message: The invalid message
  274. * @returns {boolean}
  275. */
  276. validate: function(validateInstance, element, options) {
  277. var value = $(element).val();
  278. return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(value);
  279. }
  280. }
  281. });
  282. }(window.jQuery));
  283. ;(function($) {
  284. $.extend($.bootstrapValidator.validator, {
  285. identical: {
  286. /**
  287. * Check if input value equals to value of particular one
  288. *
  289. * @param {bootstrapValidator} validateInstance Validate plugin instance
  290. * @param {HTMLElement} element
  291. * @param {Object} options Consists of the following key:
  292. * - field: The name of field that will be used to compare with current one
  293. * @returns {boolean}
  294. */
  295. validate: function(validateInstance, element, options) {
  296. var value = $(element).val(),
  297. $compareWith = validateInstance.getForm().find('[name="' + options.field + '"]');
  298. if (value == $compareWith.val()) {
  299. validateInstance.removeError($compareWith);
  300. return true;
  301. } else {
  302. return false;
  303. }
  304. }
  305. }
  306. });
  307. }(window.jQuery));
  308. ;(function($) {
  309. $.extend($.bootstrapValidator.validator, {
  310. lessThan: {
  311. /**
  312. * Return true if the input value is less than or equal to given number
  313. *
  314. * @param {bootstrapValidator} validateInstance Validate plugin instance
  315. * @param {HTMLElement} element
  316. * @param {Object} options Can consist of the following keys:
  317. * - value: The number used to compare to
  318. * - inclusive [optional]: Can be true or false. Default is true
  319. * - message: The invalid message
  320. * @returns {boolean}
  321. */
  322. validate: function(validateInstance, element, options) {
  323. var value = parseFloat($(element).val());
  324. return (options.inclusive === true) ? (value < options.value) : (value <= options.value);
  325. }
  326. }
  327. });
  328. }(window.jQuery));
  329. ;(function($) {
  330. $.extend($.bootstrapValidator.validator, {
  331. notEmpty: {
  332. /**
  333. * Check if input value is empty or not
  334. *
  335. * @param {bootstrapValidator} validateInstance Validate plugin instance
  336. * @param {HTMLElement} element
  337. * @param {Object} options
  338. * @returns {boolean}
  339. */
  340. validate: function(validateInstance, element, options) {
  341. var $element = $(element),
  342. type = $element.attr('type');
  343. return ('checkbox' == type || 'radio' == type)
  344. ? $element.is(':checked')
  345. : ($.trim($(element).val()) != '');
  346. }
  347. }
  348. });
  349. }(window.jQuery));
  350. ;(function($) {
  351. $.extend($.bootstrapValidator.validator, {
  352. regexp: {
  353. /**
  354. * Check if the element value matches given regular expression
  355. *
  356. * @param {bootstrapValidator} validateInstance Validate plugin instance
  357. * @param {HTMLElement} element
  358. * @param {Object} options Consists of the following key:
  359. * - regexp: The regular expression you need to check
  360. * @returns {boolean}
  361. */
  362. validate: function(validateInstance, element, options) {
  363. var value = $.trim($(element).val());
  364. return value.match(options.regexp);
  365. }
  366. }
  367. });
  368. }(window.jQuery));
  369. ;(function($) {
  370. $.extend($.bootstrapValidator.validator, {
  371. remote: {
  372. /**
  373. * Request a remote server to check the input value
  374. *
  375. * @param {bootstrapValidator} validateInstance Validate plugin instance
  376. * @param {HTMLElement} element
  377. * @param {Object} options Can consist of the following keys:
  378. * - url
  379. * - data [optional]: By default, it will take the value
  380. * {
  381. * <fieldName>: <fieldValue>
  382. * }
  383. * - message: The invalid message
  384. * @returns {string}
  385. */
  386. validate: function(validateInstance, element, options) {
  387. var value = $(element).val(), name = $(element).attr('name');
  388. if (!options.data) {
  389. options.data = {};
  390. options.data[name] = value;
  391. }
  392. var xhr = $.ajax({
  393. type: 'POST',
  394. url: options.url,
  395. dataType: 'json',
  396. data: options.data
  397. }).success(function(response) {
  398. validateInstance.completeRequest(element, 'remote');
  399. if (response.valid === true || response.valid === 'true') {
  400. validateInstance.showError(element, 'remote');
  401. }
  402. });
  403. validateInstance.startRequest(element, 'remote', xhr);
  404. return 'pending';
  405. }
  406. }
  407. });
  408. }(window.jQuery));
  409. ;(function($) {
  410. $.extend($.bootstrapValidator.validator, {
  411. stringLength: {
  412. /**
  413. * Check if the length of element value is less or more than given number
  414. *
  415. * @param {bootstrapValidator} validateInstance Validate plugin instance
  416. * @param {HTMLElement} element
  417. * @param {Object} options Consists of following keys:
  418. * - min
  419. * - max
  420. * At least one of two keys is required
  421. * @returns {boolean}
  422. */
  423. validate: function(validateInstance, element, options) {
  424. var value = $.trim($(element).val()), length = value.length;
  425. if ((options.min && length < options.min) || (options.max && length > options.max)) {
  426. return false;
  427. }
  428. return true;
  429. }
  430. }
  431. });
  432. }(window.jQuery));
  433. ;(function($) {
  434. $.extend($.bootstrapValidator.validator, {
  435. uri: {
  436. /**
  437. * Return true if the input value is a valid URL
  438. *
  439. * @param {bootstrapValidator} validateInstance Validate plugin instance
  440. * @param {HTMLElement} element
  441. * @param {Object} options
  442. * @returns {boolean}
  443. */
  444. validate: function(validateInstance, element, options) {
  445. // Credit to https://gist.github.com/dperini/729294
  446. //
  447. // Regular Expression for URL validation
  448. //
  449. // Author: Diego Perini
  450. // Updated: 2010/12/05
  451. //
  452. // the regular expression composed & commented
  453. // could be easily tweaked for RFC compliance,
  454. // it was expressly modified to fit & satisfy
  455. // these test for an URL shortener:
  456. //
  457. // http://mathiasbynens.be/demo/url-regex
  458. //
  459. // Notes on possible differences from a standard/generic validation:
  460. //
  461. // - utf-8 char class take in consideration the full Unicode range
  462. // - TLDs have been made mandatory so single names like "localhost" fails
  463. // - protocols have been restricted to ftp, http and https only as requested
  464. //
  465. // Changes:
  466. //
  467. // - IP address dotted notation validation, range: 1.0.0.0 - 223.255.255.255
  468. // first and last IP address of each class is considered invalid
  469. // (since they are broadcast/network addresses)
  470. //
  471. // - Added exclusion of private, reserved and/or local networks ranges
  472. //
  473. // Compressed one-line versions:
  474. //
  475. // Javascript version
  476. //
  477. // /^(?:(?: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
  478. //
  479. // PHP version
  480. //
  481. // _^(?:(?: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
  482. var urlExp = new RegExp(
  483. "^" +
  484. // protocol identifier
  485. "(?:(?:https?|ftp)://)" +
  486. // user:pass authentication
  487. "(?:\\S+(?::\\S*)?@)?" +
  488. "(?:" +
  489. // IP address exclusion
  490. // private & local networks
  491. "(?!10(?:\\.\\d{1,3}){3})" +
  492. "(?!127(?:\\.\\d{1,3}){3})" +
  493. "(?!169\\.254(?:\\.\\d{1,3}){2})" +
  494. "(?!192\\.168(?:\\.\\d{1,3}){2})" +
  495. "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" +
  496. // IP address dotted notation octets
  497. // excludes loopback network 0.0.0.0
  498. // excludes reserved space >= 224.0.0.0
  499. // excludes network & broacast addresses
  500. // (first & last IP address of each class)
  501. "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
  502. "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
  503. "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
  504. "|" +
  505. // host name
  506. "(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)" +
  507. // domain name
  508. "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*" +
  509. // TLD identifier
  510. "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" +
  511. ")" +
  512. // port number
  513. "(?::\\d{2,5})?" +
  514. // resource path
  515. "(?:/[^\\s]*)?" +
  516. "$", "i"
  517. );
  518. return urlExp.test($(element).val());
  519. }
  520. }
  521. });
  522. }(window.jQuery));
  523. ;(function($) {
  524. $.extend($.bootstrapValidator.validator, {
  525. usZipCode: {
  526. /**
  527. * Return true if and only if the input value is a valid US zip code
  528. *
  529. * @param {bootstrapValidator} validateInstance Validate plugin instance
  530. * @param {HTMLElement} element
  531. * @param {Object} options
  532. * @returns {boolean}
  533. */
  534. validate: function(validateInstance, element, options) {
  535. var value = $(element).val();
  536. return /^\d{5}([\-]\d{4})?$/.test(value);
  537. }
  538. }
  539. });
  540. }(window.jQuery));