Reputation: 532
Please provide me regular expression to validate email id like below in web api method:
// GET: users/sample%40email.com
[Route("users/{emailAddress:regex()}")]
public IHttpActionResult GetUser(string emailAddress)
Here i need regular expression which will validate email like sample%40email.com and will work in :regex() of web api route attribute.
Upvotes: 1
Views: 8513
Reputation: 532
Below solution worked for me. Thanks for the help.
// GET: users/sample%40email.com
[Route("users/{emailAddress:regex(\\[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4})}")]
public IHttpActionResult GetUser(string emailAddress)
Upvotes: 3
Reputation: 2900
What version of framework do you use? If this is framework 4.5 you apply Email attribute
[EmailAddress(ErrorMessage = "Not a valid email")]
RegEx will look like this
^[a-zA-Z0-9_.+-]+@[email]+\.[a-zA-Z0-9-.]+$
Upvotes: 11
Reputation: 5312
You have several options to validate the email address. You can use regex or MailAddress Class.
Regex
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
Usage
bool isEmail = Regex.IsMatch(emailAddress, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase);
Using MailAddress
public bool IsValid(string emailAddress)
{
try
{
MailAddress m = new MailAddress(emailaddress);
return true;
}
catch (FormatException)
{
return false;
}
}
Upvotes: 4