Thursday, July 3, 2014

Validate single & multiple email addresses using regular expression

One of the things I've noticed is within AX they don't do much validation of email addresses so I can enter test@123 and it would recognize it as a valid email. So if you do any sort of custom notifications the code samples below will show you have to make sure you don't try to send anything to an invalid email. You can also use the following website to check any regular expression http://rubular.com/ syntax

Check single email address

public boolean isValidEmail(str emailAddress)
{
    boolean isValidInput;
    System.Text.RegularExpressions.Match myMatch;
    str validEmailPattern = @"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"; //pattern check for a valid email address
    try
    {
        //call function to see if the input matches the reg ex pattern
        myMatch = System.Text.RegularExpressions.Regex::Match(emailAddress, validEmailPattern);
        //check to see what the status of matching the pattern was
        isValidInput = myMatch.get_Success();
        //return to the call if the value follows the email pattern
        return isValidInput;
    }
    catch
    {
        //there was an error parsing this email so return false
        return false;
    }
}



How to check multiple emails:
(pass in a container of email addresses and return the invalid email addresses. If the container being returned has a conlen() of 0 then all of the emails are valid. You could also easily change this so it just returns a boolean if you like.


public static container checkEmailValidity(container emailAddresses)
{
    str currentEmail;
    container  invalidEmailAddresses;
    Counter emailCounter = 1;
    //check all of the email addresses against the email regular expression
    while (emailCounter <= conLen(emailAddresses))
    {
        //read the current email address from the container
        currentEmail = conPeek(emailAddresses, emailCounter);
        //check to see if the email is invalid and if it is then add it to the list
        if(!this.isValidEmail(currentEmail) && currentEmail !="")
        {
           invalidEmailAddresses += currentEmail;
        }
        ++emailCounter;
    }
    return invalidEmailAddresses;
}


No comments:

Post a Comment