bootstrapValidator.js 21 KB

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