Home > Software design >  Regular expression prevent non English letters from email
Regular expression prevent non English letters from email

Time:11-20

In our project, we use this regular expression to validate emails:

"^([\w-\.] )@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-] \.) ))([a-zA-Z]{2,7}|[0-9]{1,3})(\]?)$"

But it allows non English characters.

For example:

"مستخدم@mail.com"

"userمحمد@mail.com"

"userName@خادم.com"

are valid emails.

How to add another rule to this expression to limit inputs to English letters only?

CodePudding user response:

Can do like this

        string[] StrInputNumber = { "[email protected]", "مستخدم@mail.com'", "userمحمد@mail.com", "userName@خادم.com" };
        Regex ASCIILettersOnly = new Regex(@"^[\P{L}A-Za-z]*$");
        foreach (String item in StrInputNumber) {
        if (ASCIILettersOnly.IsMatch(item)) {
         Console.WriteLine(item   " ==> valid");
        }
        else {
         Console.WriteLine(item   " ==>not valid");
        }
        }

Output

enter image description here

for some basic explanation about regex Click Here

CodePudding user response:

You can use this website to test your regular expression

if you don't need to keep your current expression you can use this one instead: ^[A-Z0-9._% -] @[A-Z0-9.-] .[A-Z]{2,4}$.

I tested it with your examples and it works as you want.

  • Related