开发者

Problem in regex Email validator in C#

I'm using the following code for validating email address which are present in an array. But after successfully validating first email address in an array, it is always returning false for next email address. May I know why it is behaving like that?

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 is getting email address from windows form text box:

String[] E开发者_JS百科mailArr = txtEmailID.Text.Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries);

            for(int i = 0; i < EmailArr.Length; i++)
            {
               MessageBox.Show(IsValidEmailID(EmailArr[i])+" "+EmailArr[i]);
            }


This validation method works OK. I created an ArrayList and looping through array I'm calling your method to validate email. Here is sample 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);
        }

First time result equals to true, second to false and third to true. What kind of collection are you using? Maybe all emails except the first one are invalid....?

UPDATE:

I tested with 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 think I may suggest is to trim string before validating. Textboxes sometimes have some extra spaces, which may cause issues.

IsVAludEmailID(EmailArr[i].Trim())
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜