Home > DeveloperSection > Forums > The specified string is not in the form required for an e-mail address
Pravesh Singh
Pravesh Singh

Total Post:101

Points:709
Posted on    August-26-2014 2:24 AM

 ASP.Net ASP.Net 
Ratings:


 1 Reply(s)
 1627  View(s)
Rate this:

The specified string is not in the form required for an e-mail address. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: The specified string is not in the form required for an e-mail address.



Sumit Kesarwani

Total Post:378

Points:2694
Posted on    August-26-2014 2:58 AM

Hi Pravesh, 

The specified string is not in the form required for an e-mail address

The problematic code was as follows:

MailMessage objMsg = new MailMessage(regEmail.Text.ToString(), "me@mysite.com");

I fixed the issue by replacing that code with this:

MailMessage objMsg = new MailMessage();

objMsg.From = new MailAddress(regEmail.Text.ToString());

objMsg.To.Add(new MailAddress("me@mysite.com"));

It is also helpful to use a regular expression validator in your user control to make sure the address is valid, you can use the following code for asp:

<asp:RegularExpressionValidator ID="regex1" ControlToValidate="regEmail" ErrorMessage="Please enter a valid email address" ValidationExpression="^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$" ValidationGroup="regGroup" runat="server" Display="None" SetFocusOnError="True"></asp:RegularExpressionValidator>

Or if you'd prefer to validate the email in C#

public static bool IsValidEmail(String Email)

{

    if( Email != null && Email != "" )

        return Regex.IsMatch(Email, @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" );

    else

        return false;

}


Don't want to miss updates? Please click the below button!

Follow MindStick