Tuesday, August 20, 2019

use c# Regular Expressions match to validate an email or a phone number

I share here a helper method to use c# Regular Expressions.

class MYD_Functions
{
}
public static boolean matchRegularExpression(str pattern, str value)
{
    System.Text.RegularExpressions.Match myMatch;

    myMatch = System.Text.RegularExpressions.Regex::Match(value, pattern);

    return myMatch.get_Success();
}
public static boolean validateEmail(EmailBase email)
{
    Str emailPattern = @'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$';

    return MYD_Functions::matchRegularExpression(emailPattern, email);
}
public static boolean validatePhone(Phone phone)
{
    Str phonePattern = @'^([0-9-+ ]{4,20}|)$'; //only num +- space; empty or min lenght of 4 to 20 char
    return MYD_Functions::matchRegularExpression(phonePattern, phone);
}

but I suggest you always use built in methods rather then creating yours. So here the same example using the Global::isMatch method (which behind the scene is actually doing the same thing

public static boolean validateEmail(EmailBase email)
{
    Str emailPattern = @'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$';

    return Global::isMatch(email, emailPattern);
}
public static boolean validatePhone(Phone phone)
{
    Str phonePattern = @'^([0-9-+ ]{4,20}|)$'; //only num +- space; empty or min lenght of 4 to 20 char
    return Global::isMatch(phone, phonePattern);
}

No comments:

Post a Comment