bootstrapvalidate.js 20 KB

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