Guest User

Untitled

a guest
Oct 5th, 2013
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. /**
  2. * Validator for email address.
  3. * Tested against cases listed here: http://blogs.msdn.com/b/testing123/archive/2009/02/05/email-address-test-cases.aspx
  4. *
  5. * @param {string} email The email address to be validated
  6. * return {boolean}
  7. */
  8. function isValidEmailAddress(email) {
  9.  
  10. if (!email) return false;
  11.  
  12. var matches = email.match(/^([^@]+)@([a-zA-Z0-9\[][a-zA-Z0-9\-\.\]]{0,254})$/);
  13.  
  14. if (!matches || matches.length != 3) return false;
  15.  
  16. var local = matches[1];
  17. var domain = matches[2];
  18.  
  19. // If the local part has a space or " but isn't inside quotes its invalid
  20. if ((local.indexOf('"') >= 0 || local.indexOf(' ') >= 0) && (local.charAt(0) != '"' || local.charAt(local.length - 1) != '"')) {
  21. return false;
  22. }
  23.  
  24. // If there are not exactly 0 and 2 quotes, its invalid
  25. var quotesMatch = local.match(/"/g);
  26. if (quotesMatch && quotesMatch.length != 2) {
  27. return false;
  28. }
  29.  
  30. // If the local part starts or ends with a dot (.), its invalid
  31. if (local.charAt(0) == '.' || local.charAt(local.length - 1) == '.') {
  32. return false;
  33. }
  34.  
  35. // Check the domain has at least 1 dot in it
  36. if (domain.indexOf('.') < 0) {
  37. return false;
  38. }
  39.  
  40. // Check that local part has valid chars
  41. if (!local.match(/^([\ \"\w\!\#\$\%\&\'\*\+\-\/\=\?\^\_\`\{\|\}\~\.]{1,64})$/)) {
  42. return false;
  43. }
  44.  
  45. // Email with consecutive dots is invalid
  46. if (email.match(/[\.][\.]+/g)) {
  47. return false;
  48. }
  49.  
  50. // If domain is IP check if its valid
  51. var maybeIp = domain.match(/^(\[?)([0-9\.]+)(\]?)$/);
  52. var validIp = domain.match(/^(\[?)([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})(\]?)$/);
  53. if (maybeIp && !validIp) {
  54. return false;
  55. }
  56.  
  57. return true;
  58.  
  59. };
  60.  
  61. /**
  62. * Check if the passed hex color is valid
  63. *
  64. * @param {string} hex Hexadecimal colors (without the #)
  65. */
  66. function validHexColor(hex) {
  67. var matcher = /^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/;
  68. return matcher.test(hex);
  69. };
  70.  
  71. /**
  72. * Normalize 3 chracter hex colors to 6 character hex color
  73. *
  74. * @param {string} hex
  75. * @return {string} The normalized hex color
  76. */
  77. function normalizeHexColor(hex) {
  78. if (validHexColor(hex) && hex.length == 4) {
  79. var p = hex.split('');
  80. return (p[0] + p[1] + p[1] + p[2] + p[2] + p[3] + p[3]);
  81. }
  82. return hex;
  83. };
Advertisement
Add Comment
Please, Sign In to add comment