Validating an Email using Code

vishalneeraj-24503
Posted by vishalneeraj-24503 under ASP.NET category on | Points: 40 | Views : 265
Refer below code:-
Below code will return true(if valid mail) or false(if invalid mail). Here,we have used Regular Expression IsMatch method to validate any email like below:-

using System.Text.RegularExpressions;
private bool IsValidEmail(string Email)
{
string pattern_strict = @"^(([^<>()[\]\\.,;:\s@\""]+"
+ @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
+ @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
+ @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
+ @"[a-zA-Z]{2,}))$";
Regex Valid_Email = new Regex(pattern_strict);

if (Valid_Email.IsMatch(Email))
return true;
return false;
}

Now,to check mail-id is valid or not,write :-
if (IsValidEmail("abc@c.com"))
Response.Write("Valid mail" + "</br>");
else
Response.Write("Invalid mail" + "</br>");

if (IsValidEmail("abcc.com"))
Response.Write("Valid mail" + "</br>");
else
Response.Write("Invalid mail" + "</br>");

if (IsValidEmail("@abcc.com"))
Response.Write("Valid mail" + "</br>");
else
Response.Write("Invalid mail" + "</br>");


Output:-
Valid mail
Invalid mail
Invalid mail

Comments or Responses

Login to post response