PageRenderTime 49ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/ajax/libs/jquery-form-validator/2.1.9/security.dev.js

https://gitlab.com/Mirros/cdnjs
JavaScript | 348 lines | 248 code | 45 blank | 55 comment | 57 complexity | eb4343f36f5dfd939d11c14d135aeb07 MD5 | raw file
  1. /**
  2. * jQuery Form Validator Module: Security
  3. * ------------------------------------------
  4. * Created by Victor Jonsson <http://victorjonsson.se>
  5. *
  6. * This module adds validators typically used in registration forms.
  7. * This module adds the following validators:
  8. * - spamcheck
  9. * - confirmation
  10. * - strength
  11. * - backend
  12. *
  13. * @website http://formvalidator.net/#security-validators
  14. * @license Dual licensed under the MIT or GPL Version 2 licenses
  15. * @version 2.1.9
  16. */
  17. (function($) {
  18. /*
  19. * Simple spam check
  20. */
  21. $.formUtils.addValidator({
  22. name : 'spamcheck',
  23. validatorFunction : function(val, $el, config) {
  24. var attr = $el.valAttr('captcha');
  25. return attr === val;
  26. },
  27. errorMessage : '',
  28. errorMessageKey: 'badSecurityAnswer'
  29. });
  30. /*
  31. * Validate confirmation
  32. */
  33. $.formUtils.addValidator({
  34. name : 'confirmation',
  35. validatorFunction : function(value, $el, config, language, $form) {
  36. var conf = '',
  37. confInputName = $el.attr('name') + '_confirmation',
  38. confInput = $form.find('input[name="' +confInputName+ '"]').eq(0);
  39. if (confInput) {
  40. conf = confInput.val();
  41. } else {
  42. console.warn('Could not find an input with name "'+confInputName+'"');
  43. }
  44. return value === conf;
  45. },
  46. errorMessage : '',
  47. errorMessageKey: 'notConfirmed'
  48. });
  49. /*
  50. * Validate password strength
  51. */
  52. $.formUtils.addValidator({
  53. name : 'strength',
  54. validatorFunction : function(val, $el, conf) {
  55. var requiredStrength = $el.valAttr('strength')
  56. if(requiredStrength && requiredStrength > 3)
  57. requiredStrength = 3;
  58. return $.formUtils.validators.validate_strength.calculatePasswordStrength(val) >= requiredStrength;
  59. },
  60. errorMessage : '',
  61. errorMessageKey: 'badStrength',
  62. /**
  63. * Code more or less borrowed from jQuery plugin "Password Strength Meter"
  64. * written by Darren Mason (djmason9@gmail.com), myPocket technologies (www.mypocket-technologies.com)
  65. * @param {String} password
  66. * @return {Number}
  67. */
  68. calculatePasswordStrength : function(password) {
  69. if (password.length < 4) {
  70. return 0;
  71. }
  72. var score = 0;
  73. var checkRepetition = function (pLen, str) {
  74. var res = "";
  75. for (var i = 0; i < str.length; i++) {
  76. var repeated = true;
  77. for (var j = 0; j < pLen && (j + i + pLen) < str.length; j++) {
  78. repeated = repeated && (str.charAt(j + i) == str.charAt(j + i + pLen));
  79. }
  80. if (j < pLen) {
  81. repeated = false;
  82. }
  83. if (repeated) {
  84. i += pLen - 1;
  85. repeated = false;
  86. }
  87. else {
  88. res += str.charAt(i);
  89. }
  90. }
  91. return res;
  92. };
  93. //password length
  94. score += password.length * 4;
  95. score += ( checkRepetition(1, password).length - password.length ) * 1;
  96. score += ( checkRepetition(2, password).length - password.length ) * 1;
  97. score += ( checkRepetition(3, password).length - password.length ) * 1;
  98. score += ( checkRepetition(4, password).length - password.length ) * 1;
  99. //password has 3 numbers
  100. if (password.match(/(.*[0-9].*[0-9].*[0-9])/)) {
  101. score += 5;
  102. }
  103. //password has 2 symbols
  104. if (password.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)) {
  105. score += 5;
  106. }
  107. //password has Upper and Lower chars
  108. if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) {
  109. score += 10;
  110. }
  111. //password has number and chars
  112. if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) {
  113. score += 15;
  114. }
  115. //
  116. //password has number and symbol
  117. if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([0-9])/)) {
  118. score += 15;
  119. }
  120. //password has char and symbol
  121. if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([a-zA-Z])/)) {
  122. score += 15;
  123. }
  124. //password is just a numbers or chars
  125. if (password.match(/^\w+$/) || password.match(/^\d+$/)) {
  126. score -= 10;
  127. }
  128. //verifying 0 < score < 100
  129. if (score < 0) {
  130. score = 0;
  131. }
  132. if (score > 100) {
  133. score = 100;
  134. }
  135. if (score < 20) {
  136. return 0;
  137. }
  138. else if (score < 40) {
  139. return 1;
  140. }
  141. else if(score <= 60) {
  142. return 2;
  143. }
  144. else {
  145. return 3;
  146. }
  147. },
  148. strengthDisplay : function($el, options) {
  149. var config = {
  150. fontSize: '12pt',
  151. padding: '4px',
  152. bad : 'Very bad',
  153. weak : 'Weak',
  154. good : 'Good',
  155. strong : 'Strong'
  156. };
  157. if (options) {
  158. $.extend(config, options);
  159. }
  160. $el.bind('keyup', function() {
  161. var val = $(this).val();
  162. var $parent = typeof config.parent == 'undefined' ? $(this).parent() : $(config.parent);
  163. var $displayContainer = $parent.find('.strength-meter');
  164. if($displayContainer.length == 0) {
  165. $displayContainer = $('<span></span>');
  166. $displayContainer
  167. .addClass('strength-meter')
  168. .appendTo($parent);
  169. }
  170. if( !val ) {
  171. $displayContainer.hide();
  172. } else {
  173. $displayContainer.show();
  174. }
  175. var strength = $.formUtils.validators.validate_strength.calculatePasswordStrength(val);
  176. var css = {
  177. background: 'pink',
  178. color : '#FF0000',
  179. fontWeight : 'bold',
  180. border : 'red solid 1px',
  181. borderWidth : '0px 0px 4px',
  182. display : 'inline-block',
  183. fontSize : config.fontSize,
  184. padding : config.padding
  185. };
  186. var text = config.bad;
  187. if(strength == 1) {
  188. text = config.weak;
  189. }
  190. else if(strength == 2) {
  191. css.background = 'lightyellow';
  192. css.borderColor = 'yellow';
  193. css.color = 'goldenrod';
  194. text = config.good;
  195. }
  196. else if(strength >= 3) {
  197. css.background = 'lightgreen';
  198. css.borderColor = 'darkgreen';
  199. css.color = 'darkgreen';
  200. text = config.strong;
  201. }
  202. $displayContainer
  203. .css(css)
  204. .text(text);
  205. });
  206. }
  207. });
  208. var requestServer = function(serverURL, $element, val, conf, callback) {
  209. $.ajax({
  210. url : serverURL,
  211. type : 'POST',
  212. cache : false,
  213. data : $element.attr('name')+'='+val,
  214. dataType : 'json',
  215. success : function(response) {
  216. if(response.valid) {
  217. $element.valAttr('backend-valid', 'true');
  218. }
  219. else {
  220. $element.valAttr('backend-invalid', 'true');
  221. if(response.message)
  222. $element.attr(conf.validationErrorMsgAttribute, response.message);
  223. else
  224. $element.removeAttr(conf.validationErrorMsgAttribute);
  225. }
  226. if( !$element.valAttr('has-keyup-event') ) {
  227. $element
  228. .valAttr('has-keyup-event', '1')
  229. .bind('keyup', function() {
  230. $(this)
  231. .valAttr('backend-valid', false)
  232. .valAttr('backend-invalid', false)
  233. .removeAttr(conf.validationErrorMsgAttribute);
  234. });
  235. }
  236. callback();
  237. }
  238. });
  239. },
  240. disableFormSubmit = function() {
  241. return false;
  242. };
  243. /*
  244. * Server validation
  245. * Flow (form submission):
  246. * 1) Check if the value already has been validated on the server . If so, display the validation
  247. * result and continue the validation process, otherwise continue to step 2
  248. * 2) Return false as if the value is invalid and set $.formUtils.haltValidation to true
  249. * 3) Disable form submission on the form being validated
  250. * 4) Request the server with value and input name and add class 'validating-server-side' to the form
  251. * 5) When the server responds an attribute will be added to the element
  252. * telling the validator that the input has a valid/invalid value and enable form submission
  253. * 6) Run form submission again (back to step 1)
  254. */
  255. $.formUtils.addValidator({
  256. name : 'server',
  257. validatorFunction : function(val, $el, conf, lang, $form) {
  258. var backendValid = $el.valAttr('backend-valid'),
  259. backendInvalid = $el.valAttr('backend-invalid'),
  260. serverURL = document.location.href;
  261. if($el.valAttr('url')) {
  262. serverURL = $el.valAttr('url');
  263. } else if('serverURL' in conf) {
  264. serverURL = conf.backendUrl;
  265. }
  266. if(backendValid)
  267. return true;
  268. else if(backendInvalid)
  269. return false;
  270. if($.formUtils.isValidatingEntireForm) {
  271. $form
  272. .bind('submit', disableFormSubmit)
  273. .addClass('validating-server-side')
  274. .addClass('on-blur');
  275. requestServer(serverURL, $el, val, conf, function() {
  276. $form
  277. .removeClass('validating-server-side')
  278. .removeClass('on-blur')
  279. .get(0).onsubmit = function() {};
  280. $form.unbind('submit', disableFormSubmit);
  281. // fire submission again!
  282. $form.trigger('submit');
  283. });
  284. $.formUtils.haltValidation = true;
  285. return false;
  286. } else {
  287. // validaiton on blur
  288. $form.addClass('validating-server-side');
  289. requestServer(serverURL, $el, val, conf, function() {
  290. $form.removeClass('validating-server-side');
  291. $el.trigger('blur');
  292. });
  293. return true;
  294. }
  295. },
  296. errorMessage : '',
  297. errorMessageKey: 'badBackend'
  298. });
  299. $.fn.displayPasswordStrength = function(conf) {
  300. new $.formUtils.validators.validate_strength.strengthDisplay(this, conf);
  301. return this;
  302. };
  303. })(jQuery);