In C# windows forms how a MaskedTextBox for email address can be implemented

Sri picture Sri · Nov 22, 2012 · Viewed 13.3k times · Source
   public void Form1_Load(Object sender, EventArgs e) 
    {
          // Other initialization code
         mtxtEmailID.Mask = ".........."; 

what should be the Mask Type in place of dots

         mtxtEmailID.MaskInputRejected += new MaskInputRejectedEventHandler(mtxtEmailID_MaskInputRejected)
    }

   void mtxtEmailID_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
   {
      if(!Regex.IsMatch(txtEmailID.Text, "^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"))  

the regex here gives me error, let me know what is the right one for email validation.

         {
         toolTip1.ToolTipTitle = "Invalid Input";
         toolTip1.Show("Enter valid email address", mtxtEMailID);
         }
   }

Answer

Anirudha picture Anirudha · Nov 22, 2012

You can find info about MaskedTextBox here


If you want to validate an Email Address Regex is not the right choice.There are many corner cases that the regex wont cover...

Use MailAddress

try 
{
   address = new MailAddress(address).Address;
   //email address is valid since the above line has not thrown an exception
} 
catch(FormatException) 
{
   //address is invalid
}

But if you need regex, it should be:

.+@.+