bootstrapValidator.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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() || that.numPendingRequests == null) {
  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. if (isValid === false ) {
  159. this.showError($field, validatorName);
  160. } else if (isValid === true ) {
  161. this.removeError($field);
  162. }
  163. var field = $field.attr('name');
  164. this.numPendingRequests--;
  165. if (this.numPendingRequests < 0) {
  166. this.numPendingRequests = 0;
  167. }
  168. delete this.xhrRequests[field][validatorName];
  169. },
  170. isValid: function() {
  171. if (this.numPendingRequests > 0) {
  172. return false;
  173. }
  174. for (var field in this.invalidFields) {
  175. if (this.invalidFields[field]) {
  176. return false;
  177. }
  178. }
  179. return true;
  180. }
  181. };
  182. // Plugin definition
  183. $.fn.bootstrapValidator = function(options) {
  184. return this.each(function() {
  185. var $this = $(this), data = $this.data('bootstrapValidator');
  186. if (!data) {
  187. $this.data('bootstrapValidator', (data = new BootstrapValidator(this, options)));
  188. }
  189. });
  190. };
  191. // Available validators
  192. $.fn.bootstrapValidator.validators = {};
  193. $.fn.bootstrapValidator.Constructor = BootstrapValidator;
  194. }(window.jQuery));
  195. ;(function($) {
  196. $.fn.bootstrapValidator.validators.between = {
  197. /**
  198. * Return true if the input value is between (strictly or not) two given numbers
  199. *
  200. * @param {BootstrapValidator} validator The validator plugin instance
  201. * @param {jQuery} $field Field element
  202. * @param {Object} options Can consist of the following keys:
  203. * - min
  204. * - max
  205. * - inclusive [optional]: Can be true or false. Default is true
  206. * - message: The invalid message
  207. * @returns {boolean}
  208. */
  209. validate: function(validator, $field, options) {
  210. var value = parseFloat($field.val());
  211. return (options.inclusive === true)
  212. ? (value > options.min && value < options.max)
  213. : (value >= options.min && value <= options.max);
  214. }
  215. };
  216. }(window.jQuery));
  217. ;(function($) {
  218. $.fn.bootstrapValidator.validators.digits = {
  219. /**
  220. * Return true if the input value contains digits only
  221. *
  222. * @param {BootstrapValidator} validator Validate plugin instance
  223. * @param {jQuery} $field Field element
  224. * @param {Object} options
  225. * @returns {boolean}
  226. */
  227. validate: function(validator, $field, options) {
  228. return /^\d+$/.test($field.val());
  229. }
  230. }
  231. }(window.jQuery));
  232. ;(function($) {
  233. $.fn.bootstrapValidator.validators.emailAddress = {
  234. /**
  235. * Return true if and only if the input value is a valid email address
  236. *
  237. * @param {BootstrapValidator} validator Validate plugin instance
  238. * @param {jQuery} $field Field element
  239. * @param {Object} options
  240. * @returns {boolean}
  241. */
  242. validate: function(validator, $field, options) {
  243. var value = $field.val(),
  244. // Email address regular expression
  245. // http://stackoverflow.com/questions/46155/validate-email-address-in-javascript
  246. 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,}))$/;
  247. return emailRegExp.test(value);
  248. }
  249. }
  250. }(window.jQuery));
  251. ;(function($) {
  252. $.fn.bootstrapValidator.validators.greaterThan = {
  253. /**
  254. * Return true if the input value is greater than or equals to given number
  255. *
  256. * @param {BootstrapValidator} validator Validate plugin instance
  257. * @param {jQuery} $field Field element
  258. * @param {Object} options Can consist of the following keys:
  259. * - value: The number used to compare to
  260. * - inclusive [optional]: Can be true or false. Default is true
  261. * - message: The invalid message
  262. * @returns {boolean}
  263. */
  264. validate: function(validator, $field, options) {
  265. var value = parseFloat($field.val());
  266. return (options.inclusive === true) ? (value > options.value) : (value >= options.value);
  267. }
  268. }
  269. }(window.jQuery));
  270. ;(function($) {
  271. $.fn.bootstrapValidator.validators.hexColor = {
  272. /**
  273. * Return true if the input value is a valid hex color
  274. *
  275. * @param {BootstrapValidator} validator The validator plugin instance
  276. * @param {jQuery} $field Field element
  277. * @param {Object} options Can consist of the following keys:
  278. * - message: The invalid message
  279. * @returns {boolean}
  280. */
  281. validate: function(validator, $field, options) {
  282. var value = $field.val();
  283. return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(value);
  284. }
  285. };
  286. }(window.jQuery));
  287. ;(function($) {
  288. $.fn.bootstrapValidator.validators.identical = {
  289. /**
  290. * Check if input value equals to value of particular one
  291. *
  292. * @param {BootstrapValidator} validator The validator plugin instance
  293. * @param {jQuery} $field Field element
  294. * @param {Object} options Consists of the following key:
  295. * - field: The name of field that will be used to compare with current one
  296. * @returns {boolean}
  297. */
  298. validate: function(validator, $field, options) {
  299. var value = $field.val(),
  300. $compareWith = validator.getFieldElement(options.field);
  301. if ($compareWith && value == $compareWith.val()) {
  302. validator.removeError($compareWith);
  303. return true;
  304. } else {
  305. return false;
  306. }
  307. }
  308. };
  309. }(window.jQuery));
  310. ;(function($) {
  311. $.fn.bootstrapValidator.validators.lessThan = {
  312. /**
  313. * Return true if the input value is less than or equal to given number
  314. *
  315. * @param {BootstrapValidator} validator The validator plugin instance
  316. * @param {jQuery} $field Field element
  317. * @param {Object} options Can consist of the following keys:
  318. * - value: The number used to compare to
  319. * - inclusive [optional]: Can be true or false. Default is true
  320. * - message: The invalid message
  321. * @returns {boolean}
  322. */
  323. validate: function(validator, $field, options) {
  324. var value = parseFloat($field.val());
  325. return (options.inclusive === true) ? (value < options.value) : (value <= options.value);
  326. }
  327. };
  328. }(window.jQuery));
  329. ;(function($) {
  330. $.fn.bootstrapValidator.validators.notEmpty = {
  331. /**
  332. * Check if input value is empty or not
  333. *
  334. * @param {BootstrapValidator} validator The validator plugin instance
  335. * @param {jQuery} $field Field element
  336. * @param {Object} options
  337. * @returns {boolean}
  338. */
  339. validate: function(validator, $field, options) {
  340. var type = $field.attr('type');
  341. return ('checkbox' == type || 'radio' == type) ? $field.is(':checked') : ($.trim($field.val()) != '');
  342. }
  343. };
  344. }(window.jQuery));
  345. ;(function($) {
  346. $.fn.bootstrapValidator.validators.regexp = {
  347. /**
  348. * Check if the element value matches given regular expression
  349. *
  350. * @param {BootstrapValidator} validator The validator plugin instance
  351. * @param {jQuery} $field Field element
  352. * @param {Object} options Consists of the following key:
  353. * - regexp: The regular expression you need to check
  354. * @returns {boolean}
  355. */
  356. validate: function(validator, $field, options) {
  357. var value = $field.val();
  358. return value.match(options.regexp);
  359. }
  360. };
  361. }(window.jQuery));
  362. ;(function($) {
  363. $.fn.bootstrapValidator.validators.remote = {
  364. /**
  365. * Request a remote server to check the input value
  366. *
  367. * @param {BootstrapValidator} validator Plugin instance
  368. * @param {jQuery} $field Field element
  369. * @param {Object} options Can consist of the following keys:
  370. * - url
  371. * - data [optional]: By default, it will take the value
  372. * {
  373. * <fieldName>: <fieldValue>
  374. * }
  375. * - message: The invalid message
  376. * @returns {string}
  377. */
  378. validate: function(validator, $field, options) {
  379. var value = $field.val(), name = $field.attr('name');
  380. var data = options.data;
  381. if (data == null) {
  382. data = {};
  383. data[name] = value;
  384. }
  385. var xhr = $.ajax({
  386. type: 'POST',
  387. url: options.url,
  388. dataType: 'json',
  389. data: data
  390. }).success(function(response) {
  391. var isValid = response.valid === true || response.valid === 'true';
  392. validator.completeRequest($field, 'remote', isValid);
  393. });
  394. validator.startRequest($field, 'remote', xhr);
  395. return 'pending';
  396. }
  397. };
  398. }(window.jQuery));
  399. ;(function($) {
  400. $.fn.bootstrapValidator.validators.stringLength = {
  401. /**
  402. * Check if the length of element value is less or more than given number
  403. *
  404. * @param {BootstrapValidator} validator The validator plugin instance
  405. * @param {jQuery} $field Field element
  406. * @param {Object} options Consists of following keys:
  407. * - min
  408. * - max
  409. * At least one of two keys is required
  410. * @returns {boolean}
  411. */
  412. validate: function(validator, $field, options) {
  413. var value = $.trim($field.val()), length = value.length;
  414. if ((options.min && length < options.min) || (options.max && length > options.max)) {
  415. return false;
  416. }
  417. return true;
  418. }
  419. };
  420. }(window.jQuery));
  421. ;(function($) {
  422. $.fn.bootstrapValidator.validators.uri = {
  423. /**
  424. * Return true if the input value is a valid URL
  425. *
  426. * @param {BootstrapValidator} validator The validator plugin instance
  427. * @param {jQuery} $field Field element
  428. * @param {Object} options
  429. * @returns {boolean}
  430. */
  431. validate: function(validator, $field, options) {
  432. // Credit to https://gist.github.com/dperini/729294
  433. //
  434. // Regular Expression for URL validation
  435. //
  436. // Author: Diego Perini
  437. // Updated: 2010/12/05
  438. //
  439. // the regular expression composed & commented
  440. // could be easily tweaked for RFC compliance,
  441. // it was expressly modified to fit & satisfy
  442. // these test for an URL shortener:
  443. //
  444. // http://mathiasbynens.be/demo/url-regex
  445. //
  446. // Notes on possible differences from a standard/generic validation:
  447. //
  448. // - utf-8 char class take in consideration the full Unicode range
  449. // - TLDs have been made mandatory so single names like "localhost" fails
  450. // - protocols have been restricted to ftp, http and https only as requested
  451. //
  452. // Changes:
  453. //
  454. // - IP address dotted notation validation, range: 1.0.0.0 - 223.255.255.255
  455. // first and last IP address of each class is considered invalid
  456. // (since they are broadcast/network addresses)
  457. //
  458. // - Added exclusion of private, reserved and/or local networks ranges
  459. //
  460. // Compressed one-line versions:
  461. //
  462. // Javascript version
  463. //
  464. // /^(?:(?: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
  465. //
  466. // PHP version
  467. //
  468. // _^(?:(?: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
  469. var urlExp = new RegExp(
  470. "^" +
  471. // protocol identifier
  472. "(?:(?:https?|ftp)://)" +
  473. // user:pass authentication
  474. "(?:\\S+(?::\\S*)?@)?" +
  475. "(?:" +
  476. // IP address exclusion
  477. // private & local networks
  478. "(?!10(?:\\.\\d{1,3}){3})" +
  479. "(?!127(?:\\.\\d{1,3}){3})" +
  480. "(?!169\\.254(?:\\.\\d{1,3}){2})" +
  481. "(?!192\\.168(?:\\.\\d{1,3}){2})" +
  482. "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" +
  483. // IP address dotted notation octets
  484. // excludes loopback network 0.0.0.0
  485. // excludes reserved space >= 224.0.0.0
  486. // excludes network & broacast addresses
  487. // (first & last IP address of each class)
  488. "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
  489. "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
  490. "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
  491. "|" +
  492. // host name
  493. "(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)" +
  494. // domain name
  495. "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*" +
  496. // TLD identifier
  497. "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" +
  498. ")" +
  499. // port number
  500. "(?::\\d{2,5})?" +
  501. // resource path
  502. "(?:/[^\\s]*)?" +
  503. "$", "i"
  504. );
  505. return urlExp.test($field.val());
  506. }
  507. };
  508. }(window.jQuery));
  509. ;(function($) {
  510. $.fn.bootstrapValidator.validators.usZipCode = {
  511. /**
  512. * Return true if and only if the input value is a valid US zip code
  513. *
  514. * @param {BootstrapValidator} validator The validator plugin instance
  515. * @param {jQuery} $field Field element
  516. * @param {Object} options
  517. * @returns {boolean}
  518. */
  519. validate: function(validateInstance, $field, options) {
  520. var value = $field.val();
  521. return /^\d{5}([\-]\d{4})?$/.test(value);
  522. }
  523. };
  524. }(window.jQuery));