bootstrapValidator.js 21 KB

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