bootstrapValidator.js 22 KB

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