bootstrapvalidate.js 23 KB

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