Problem in Regular Expression Email Validator in C #

I use the following code to check the email address that is present in the array. But after successfully checking the first email address in the array, it always returns false for the next email address. Can I find out why he behaves this way?

public static bool IsValidEmailID(string email) { 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})$"; Regex reStrict = new Regex(MatchEmailPattern); return reStrict.IsMatch(email); } 

Update: The following code gets the email address from the text box of the window form:

 String[] EmailArr = txtEmailID.Text.Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries); for(int i = 0; i < EmailArr.Length; i++) { MessageBox.Show(IsValidEmailID(EmailArr[i])+" "+EmailArr[i]); } 
+4
source share
1 answer

This verification method works fine. I created an ArrayList array and loop through the array. I call your method to check email. Here is an example loop:

 bool result = false; ArrayList emails = new ArrayList(); emails.Add(" test@test.org "); emails.Add("Hello.com"); emails.Add(" hello@hotmail.com "); foreach (string email in emails) { result = IsValidEmailID(email); } 

The result of the first time is true, the second is false, and the third is true. What collection are you using? Perhaps all emails except the first are invalid ....?

UPDATE:

I tested your code

 string textEmail = " test@test.org ,Hello.com, hello@hotmail.com "; String[] EmailArr = textEmail.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < EmailArr.Length; i++) { Console.WriteLine(IsValidEmailID(EmailArr[i]) + " " + EmailArr[i]); } 

Your split works well. The only thing I can offer is to trim the string before validation. Sometimes text cells have extra spaces, which can cause problems.

 IsVAludEmailID(EmailArr[i].Trim()) 
+1
source

Source: https://habr.com/ru/post/1342589/


All Articles