Check if it's an e-mail

Hey, I am wondering how can I make my code so it can tell if a user has entered a real e-mail. It does not have to be existing, I need my code to check if there’s that suffix at the end “@something.something”. I could always have a list of different e-mail services, but they are so many…it’s not a good approach.

From Email Address Validation Using Regular Expression - CodeProject

/*
 * File: TestEmail.cs
 * Author: Mykola Dobrochynskyy
 * Version 1.0 
 * Created date:  07.01.2008
 * Last upadte date: 
 * Project: Common Utils
 * Description: Implements the static class, that could be used to check an E-Mail address.
 * -----------------------------------------------------------------------------
 * You are eligible to use this code for you own purpouse assuming that this
 * code and information in it is provided "AS IS" without warranty of any kind 
 * expressed or implied.
 * ------------------------------------------------------------------------------
 */
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Dobro.Text.RegularExpressions
{
    /// <summary>
    /// Tests an E-Mail address.
    /// </summary>
    public static class TestEmail
    {
        /// <summary>
        /// Regular expression, which is used to validate an E-Mail address.
        /// </summary>
        public const string MatchEmailPattern =
            @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
            + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
              + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
            + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";


        /// <summary>
        /// Checks whether the given Email-Parameter is a valid E-Mail address.
        /// </summary>
        /// <param name="email">Parameter-string that contains an E-Mail address.</param>
        /// <returns>True, wenn Parameter-string is not null and contains a valid E-Mail address;
        /// otherwise false.</returns>
        public static bool IsEmail(string email)
        {
            if (email != null) return Regex.IsMatch(email, MatchEmailPattern);
            else return false;
        }
    }
}
5 Likes

Here is something I whipped up right quick for you. The function you need is VerifyEmailAddress(address:String).

Just call that function and hand it in an email address to check and it will return true if, there is first an @ symbol, and than it will verify that there is at least one dot (.) in the string after the @ symbol. It than checks to make sure that the last part of the data, after the last dot, actually has some characters in it.

To test it, save it to VerifyEmailAddress.js, and apply it to any game object. Hit play, and enter in an address to check in the inspector. Hit “v” on the keyboard to verify the address entered. It will print the result to the console.

Examples:

foo@ will return false
foo@foo. will return false
foo@foo.a will return true
foo@foo.com will return true
foo@foo.co.uk will return true

There are still a few more checks you can put in if you’d like to verify that the data after the last dot is longer than one character, etc. This should get you moving in the right direction.

var result:boolean;
var toCheck:String;

function Update(){
    if(Input.GetKeyUp("v")){
        result = VerifyEmailAddress(toCheck);
        print("Checked " + toCheck + " result is " + result);
    }
}


static function VerifyEmailAddress(address:String){
    var atCharacter:String[];
    var dotCharacter:String[];
    atCharacter = address.Split("@"[0]);
    if(atCharacter.Length == 2){
        dotCharacter = atCharacter[1].Split("."[0]);
        if(dotCharacter.Length >= 2){
            if(dotCharacter[dotCharacter.Length - 1].Length == 0){
                return false;
            }
            else{
                return true;
            }
        }
        else{
            return false;
        }
    }
    else{
        return false;
    }
}

Hope that helps.

2 Likes

Do you want to check if it’s a valid email format or validate if it’s an actual email address? For a real test you’ll probably have to use SMTP validation. That test actually contacts the domain mailserver and finds out if the given email address is real or not…not all mailservers support this feature but I’m pretty sure most do. I’m also pretty sure you can find source code all over the net for such a test.

Sorry for the tardy reply, I had some hardware problems :frowning:
So I wanted to check if the format is right, not really if it’s an existing e-mail. Thank you guys! Melmonkey, I used your function and it worked perfectly!

I couldn’t really understand how it works though. I’ve always been awful with strings. Can you shed some light on how it works, I’ve been trying to figure it out for half an hour (lol) and I just can’t. It’s okay if you don’t want to explain it, everything works great, I’m just curious to know how it works :slight_smile:

All melmonkey’s routine does is ensure that the address contains an @ character, and that one or more periods exist after the @, but does not end with a period.

It does it by spliting the string into various arrays and checks their length. Though if you wanted to just check that, you’d be better off using the various string methods like IndexOf or EndsWith:

public static function VerifyEmailAddress(address:String)
{
	if (address == null)
	{
		return false;
	}

	var atSymbolPosition : int = address.IndexOf("@");

	//checks if the @ symbol is not found, at the start or end of the address.
	//That is, the following are not valid:
	//somewhere.com
	//@somewhere.com
	//someone@
	//someone@somewhere.com@
	if (atSymbolPosition < 1 || address.EndsWith("@"))
	{
		return false;
	}

	var periodSymbolPosition = address.IndexOf(".", atSymbolPosition);

	//checks if the period is not found, and that it's not beside the @ symbol, and it's not at the end.  
	//That is, the following are not valid:
	//someone@somewhere
	//someone@.somewhere.com
	//someone@somewhere.
	//someone@somewhere.co.
	if (periodSymbolPosition > (atSymbolPosition + 1)  !address.EndsWith("."))
	{
		return true;
	}

	return false;
}

Though honestly, this is really a job for regular expressions. You’d be better off using the method I posted as it checks for these small cases but also checks for every other case (like question marks, multiple @ symbols, etc.)

2 Likes

Got it.
So just to be sure, your code does:
1 - it checks the position of the “@” symbol from the addres variable and sets it to atSymbolPosition.
2 - than it checks if the “@” symbol is the first one and if the string ends with it, if one of these conditions are true, than the func will return false.
3 - it checks for the position of the dot after the “@” symbol. Not sure exactly what does this address.IndexOf(“.”, atSymbolPosition); return.
4 - it checks if the dot is after the “@” symbol and if the addres is not ending with a dot.

That’s alright, but how does it check if there are multiple dots? Looking at the code I have the feeling that it won’t detect if there are two dots next to each other - they will be all after the “@”.

Have I understood the code and is my guess right ? :smile:

Glad everything worked out for you.

Here is a commented script for you to peruse:

var result:boolean;
var toCheck:String;

function Update(){
    if(Input.GetKeyUp("v")){
        result = VerifyEmailAddress(toCheck);
        print("Checked " + toCheck + " result is " + result);
    }
}


static function VerifyEmailAddress(address:String){
    var atCharacter:String[];
    var dotCharacter:String[];
    // this splits the input address by the @ symbol. If it finds the @ symbol, it throws it away,
    // and puts what comes before the @ symbol into atCharacter[0], and what comes after the @ symbol
    // into atCharacter[1] 
    atCharacter = address.Split("@"[0]);
    //now we check that the returned array is exactly 2 members long, that means there was only 1 @ symbol
    if(atCharacter.Length == 2){
        //here we split the second member returned above by the dot character, and shove the returned info
        // into the dotCharacter array. 
        dotCharacter = atCharacter[1].Split("."[0]);
        // now we check the length of the dotCharacter array. If it is greater than or equal to 2, we know 
        // we have at least one dot, maybe more than one.
        if(dotCharacter.Length >= 2){
            // this last check makes sure that there is actual data after the last dot.
            if(dotCharacter[dotCharacter.Length - 1].Length == 0){
                // fail
                return false;
            }
            else{
                // if we get to here, you have a valid email address format
                return true;
            }
        }
        else{
            // fail
            return false;
        }
    }
    else{
        // fail
        return false;
    }
}

Let me know if you have any other questions.

Naw, my code doesn’t check if there are two dots right beside each other. (neither does melmonkey’s)

address.IndexOf(“.”, atSymbolPosition);

That finds the first period AFTER the @ symbol.

Again, I just want to stress that you really should use the regular expression method I posted first, it should cover all these cases plus a bajillion others.

I found that this regex worked better - it validates on having ‘+’ symbols in the email as are allowed by Gmail and other services:

    public const string MatchEmailPattern =
        "^(?(\")(\".+?(?<!\\\\)\"@)|(([0-9a-z]((\\.(?!\\.))|[-!#\\$%&'\\*\\+/=\\?\\^`{}|~\\w])*)(?<=[0-9a-z])@))(?([)([(\\d{1,3}.){3}\\d{1,3}])|(([0-9a-z][-0-9a-z]*[0-9a-z]*.)+[a-z0-9][-a-z0-9]{0,22}[a-z0-9]))$";
2 Likes
bool IsValidEmail(string email)
{
    try {
        var addr = new System.Net.Mail.MailAddress(email);
        return addr.Address == email;
    }
    catch {
        return false;
    }
}
1 Like