Here’s a little function which can be used to validate whether an email address is valid or not – it can be used as is in JavaScript or Actionscript (AS2). It checks for the following:
- The passed address is not an object
- It is not empty
- It contains an @ symbol
- It has something before the @ symbol
- It has something after the @ symbol
- It checks for opening bracket is IP address used
- It checks for Closing bracket if IP address usedIt checks for a valid full stop
- checks for valid suffix length (+ .travel and .museum)
Here’s the code:
function validEmail(e) {
retVal = true;
suffix = e.substr((e.lastIndexOf('.',e.length-1)+1),e.length);
switch(true) {
case (typeof(e) == "object"): retVal = false; break; // check it is not an object
case (e.length<1): retVal = false; break; // check it is not empty
case (e.indexOf('@',0)==-1): retVal = false; break; // check it contains an @ sign
case (e.indexOf('@',0)<1): retVal = false; break; // Nothing before the @ case (e.indexOf('@',0)==e.length-1): retVal = false; break; // Nothing after the @ case (e.indexOf('[',0)==-1&&e.charAt(e.length-1)==']'): retVal = false; break; // No Left Bracket case (e.indexOf('[',0)>-1&&e.charAt(e.length-1)!=']'): retVal = false; break; // No Right Bracket
case ((e.indexOf('@',0)>1&&e.charAt(e.length-1)!=']')&&(e.indexOf('.',0)==-1)): err="8"; retVal = false; break; // No valid full-stop
case ((e.indexOf('@',0)>1&&e.charAt(e.length-1)!=']')&&(((suffix.length<1)||(suffix.length>4))&&((suffix.toLowerCase()!='travel')&&(suffix.toLowerCase()!='museum')))): retVal = false; break; // validate the suffix
}
return retVal;
}
It will basically return true or false if the email address is valid – use it like this:
if(validEmail('my_email@address.com')) { // OK to use } else { // Nope - it's a duffer! }
It is quite a basic function but should be OK for 90% of the time – you can always add more cases in the switch to check for different things.
You can download the code here if copying from above does not work well: http://mj7.co.uk/ampy
As usual – let me know if you use it – comments and improvements are always welcome.