bootstrapvalidate.js 17 KB

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