To check if a string is valid email
address or not we can write our own string extension method and can use that
method in same way, we are using other existing methods(i.e. ToString(), ToLower() etc).
Method:
using System;
using
System.Text.RegularExpressions;
public static class StringExtensions
{
public static bool IsValidEmail(this String Email)
{
var emailRegex = new Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
return emailRegex.IsMatch(Email);
}
}
|
Usage: You can test the method like:
var testString = "test@gmail.com";
Response.Write(testString.IsValidEmail()
? "String is a valid Email"
: "String is not a valid Email");
|
Comments
Post a Comment