Created
November 26, 2009 17:39
-
-
Save pal/243586 to your computer and use it in GitHub Desktop.
Check either single email addresses or strings with multiple email addresses (coming from a textarea or similar)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Check if supplied String is a valid email adress. | |
* RegEx courtesy http://www.regular-expressions.info | |
* | |
* Use like so: is_valid_email('[email protected]'); | |
*/ | |
function is_valid_email(inputEmail:String):Boolean { | |
var emailRegEx:RegExp = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/; | |
//trace(emailRegEx.test(email)); | |
return emailRegEx.test(email); | |
} | |
/* | |
* Check if supplied String contains only valid email adresses, separated | |
* by commas, semi-colons, spaces, tabs and/or line breaks. | |
* | |
* Use like so: are_valid_emails('[email protected] [email protected], [email protected]'); | |
*/ | |
function are_valid_emails(inputEmail:String):Boolean { | |
var emailArray:Array = inputEmail.split(/,\s+|\s+|;\s+|\n+|\t+/); | |
// must be at least one email present | |
if (emailArray.length < 1) { | |
return false; | |
} | |
// validate each email address and return false if any address is not a valid email | |
for (var i:Number = 0; i < emailArray.length; i++) { | |
if (!is_valid_email(trim(emailArray[i]))) { | |
return false; | |
} | |
} | |
// all email adresses valid | |
return true; | |
} | |
/* | |
* Helper-function to trim spaces from both ends of a string. | |
*/ | |
function trim(str:String):String | |
{ | |
for(var i = 0; str.charCodeAt(i) < 33; i++); | |
for(var j = str.length-1; str.charCodeAt(j) < 33; j--); | |
return str.substring(i, j+1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment