bootstrapValidator.js 21 KB

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