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[] EmailArr = 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("[email protected]");
emails.Add("Hello.com");
emails.Add("[email protected]");
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 = "[email protected],Hello.com,[email protected]";
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())