在C#中验证文本框输入

时间:2011-06-17 06:49:35

标签: c# .net winforms validation user-input

如何使用C#中的正则表达式验证手机号码文本框和电子邮件文本框?

我想先在前端验证这些,这样数据库就不会收到任何无效的输入,甚至会检查它。

我正在使用Windows窗体。

8 个答案:

答案 0 :(得分:5)

您可以使用System.Text.RegularExpression

我将举例说明电子邮件验证

然后声明一个正则表达式,如

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

并说出您的电子邮件文本框为txtEmail

然后写,

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

<强>更新

不是正则表达式的专家,

以下是Regular expression to validate e-mail

的链接

您可以从提供的链接中找到有关regEx的更多详细信息。

答案 1 :(得分: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();
}

答案 2 :(得分:2)

此代码将检查电子邮件地址是否有效:

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");
}

(来源:http://msdn.microsoft.com/en-us/library/01escwtf.aspx

对于电话号码,它不是那么简单 - 答案取决于你在世界的哪个位置,你是否想要允许国际号码,移动电话的编号方式(例如,在美国,你无法从单独的电话号码是否是手机号码)。在维基百科上查找“电话号码计划”以获取更多信息。

答案 3 :(得分:1)

在ASP.NET中,您可以使用RegularExpressionValidator控件。

要确定正则表达式本身,您可以尝试使用Expresso等工具。

请注意,如果要允许所有可能有效的电子邮件格式,使用正则表达式验证电子邮件是一项艰巨的任务;在这种情况下,最好的办法是通过确认链接向输入的地址发送电子邮件,点击该链接后,您认为邮件有效。

答案 4 :(得分:1)

请参阅 Email Address Validation Using Regular Expression The Code Project)进行电子邮件验证,并参阅 Best practice for parsing and validating mobile number (Stack Overflow)进行手机号验证。< / p>

答案 5 :(得分:1)

我以这种方式进行数字验证,如下面的代码所示。

不需要通过char检查char,并且尊重用户文化!

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");
    }

答案 6 :(得分:0)

对于电子邮件验证,请在文本框的“丢失焦点”事件中使用以下正则表达式,如下所示。

为正则表达式使用 System.Text.RegularExpression 命名空间。

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]$");

然后使用以下代码检查

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

答案 7 :(得分:0)

对于PhoneNumber验证,请在文本框的 PreviewTextInput 事件中使用以下代码。

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;
}