2

How to validate a mobile number textbox and email textbox using regular expressions in C#?

I want to validate these first at the front end itself so that the database doesn't receive any invalid input or rather even checks for it.

I am using Windows Forms.

4
  • Is this an asp.net application, a windows forms application, or what? Commented Jun 17, 2011 at 6:54
  • What client technology are you using? Winforms, ASP.Net, WPF, ...? Commented Jun 17, 2011 at 6:54
  • @Paolo Tedesco : it's a WINFORM application Commented Jun 17, 2011 at 7:06
  • @Rewinder : it's a WINFORM application Commented Jun 17, 2011 at 7:08

8 Answers 8

5

You can use System.Text.RegularExpression

I'll give you an example for e-mail validation

then declare a regular expression like

Regex myRegularExpression = new 
                            Regex(" \b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b");

and say your e-mail textbox is txtEmail

then write,

   if(myRegularExpression.isMatch(txtEmail.Text))
   {
        //valid e-mail
   }

Update

Not an expert on regular expressions,

Here's the link to Regular expression to validate e-mail

you can find more details about the regEx from the link provided.

Sign up to request clarification or add additional context in comments.

1 Comment

can you explain me this --" \b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b" ---------what is this allowing and what not? what is \b
3
//for email validation    
System.Text.RegularExpressions.Regex rEMail = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z][\w\.-]{2,28}[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");

if (txt_email.Text.Length > 0)
{
    if (!rEMail.IsMatch(txt_email.Text))
    {
        MessageBox.Show("E-Mail expected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        txt_email.SelectAll();
        e.Cancel = true;
    }
}

//for mobile validation    
Regex re = new Regex("^9[0-9]{9}");

if (re.IsMatch(txt_mobile.Text.Trim()) == false || txt_mobile.Text.Length > 10)
{
    MessageBox.Show("Invalid Indian Mobile Number !!");
    txt_mobile.Focus();
}

Comments

2

This code will check whether an email address is valid:

string inputText = textBox1.Text;

if (Regex.IsMatch(inputText, 
                  @"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))" + 
                  @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$"))
{
  MessageBox.Show("yes");
}
else
{
  MessageBox.Show("no");
}

(source: http://msdn.microsoft.com/en-us/library/01escwtf.aspx)

For phone numbers, it's not so simple - the answer depends on where in the world you are, whether you want to allow international numbers, how mobiles are numbered (for example, in the USA, you can't tell from a phone number alone whether it's a mobile number or not). Look up "Telephone numbering plan" on Wikipedia for more information.

Comments

1

In ASP.NET you can use a RegularExpressionValidator control.

To determine the regular expression itself, you can experiment with a tool like Expresso.

Be aware that validating emails with regular expressions is a hard task, if you want to allow all the possibly valid email formats; probably the best thing to do in that case would be to send an email to the entered address with a confirmation link, and when that link is clicked, you assume that the mail is valid.

Comments

1

See Email Address Validation Using Regular Expression (The Code Project) for email validation and see Best practice for parsing and validating mobile number (Stack Overflow) for mobile number validation.

Comments

1

I do the numeric validation this way as shown in the code below.

No need for checking char by char and user culture is respected!

namespace Your_App_Namespace
{
public static class Globals
{
    public static double safeval = 0; // variable to save former value!

    public static bool isPositiveNumeric(string strval, System.Globalization.NumberStyles NumberStyle)
    // checking if string strval contains positive number in USER CULTURE NUMBER FORMAT!
    {
        double result;
        boolean test;
        if (strval.Contains("-")) test = false;
        else test = Double.TryParse(strval, NumberStyle, System.Globalization.CultureInfo.CurrentCulture, out result);
        // if (test == false) MessageBox.Show("Not positive number!");
        return test;
    }

    public static string numstr2string(string strval, string nofdec)
    // conversion from numeric string into string in USER CULTURE NUMBER FORMAT!
    // call example numstr2string("12.3456", "0.00") returns "12.34"
    {
        string retstr = "";
        if (Globals.isPositiveNumeric(strval, System.Globalization.NumberStyles.Number)) retstr = double.Parse(strval).ToString(nofdec);
        else retstr = Globals.safeval.ToString(nofdec);
        return retstr;
    }

    public static string number2string(double numval, string nofdec)
    // conversion from numeric value into string in USER CULTURE NUMBER FORMAT!
    // call example number2string(12.3456, "0.00") returns "12.34"
    {
        string retstr = "";
        if (Globals.isPositiveNumeric(numval.ToString(), System.Globalization.NumberStyles.Number)) retstr = numval.ToString(nofdec);
        else retstr = Globals.safeval.ToString(nofdec);
        return retstr;
    }
}

// Other Your_App_Namespace content

}

// This the way how to use those functions in any of your app pages

    // function to call when TextBox GotFocus

    private void textbox_clear(object sender, System.Windows.RoutedEventArgs e)
    {
        TextBox txtbox = e.OriginalSource as TextBox;
        // save original value
        Globals.safeval = double.Parse(txtbox.Text);
        txtbox.Text = "";
    }

    // function to call when TextBox LostFocus

    private void textbox_change(object sender, System.Windows.RoutedEventArgs e)
    {
        TextBox txtbox = e.OriginalSource as TextBox;
        // text from textbox into sting with checking and string format
        txtbox.Text = Globals.numstr2string(txtbox.Text, "0.00");
    }

Comments

0

For Email Validation use the following Regex Expression as below in Lost Focus event of the Textbox.

Use System.Text.RegularExpression Namespace for Regex.

Regex emailExpression = new Regex(@"^[a-zA-Z][\w\.-]{2,28}[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");

and then check it by using below code

if (emailExpression.IsMatch(textbox.Text))
{
    //Valid E-mail
}

Comments

0

For PhoneNumber Validation use the following code in PreviewTextInput event of the Textbox.

private void PhoneNumbeTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    e.Handled = !AreAllValidNumericChars(e.Text);       
}


private bool AreAllValidNumericChars(string str)
{
    bool ret = true;
    if (str == System.Globalization.NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.CurrencyGroupSeparator |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.NegativeSign |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.NegativeInfinitySymbol |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.NumberGroupSeparator |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.PercentDecimalSeparator |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.PercentGroupSeparator |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.PerMilleSymbol |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.PositiveInfinitySymbol |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.PositiveSign)
            return ret;

    int l = str.Length;
    for (int i = 0; i < l; i++)
    {
        char ch = str[i];
        ret &= Char.IsDigit(ch);
    }

    return ret;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.