C# 中文本框输入的验证

发布于 2024-11-16 06:34:05 字数 114 浏览 4 评论 0原文

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

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

我正在使用 Windows 窗体。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

拥抱影子 2024-11-23 06:34:05

您可以使用 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
   }

更新

不是正则表达式方面的专家,

这是正则表达式的链接验证电子邮件

您可以从提供的链接找到有关正则表达式的更多详细信息。

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.

一场信仰旅途 2024-11-23 06:34:05
//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();
}
//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();
}
坚持沉默 2024-11-23 06:34:05

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

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

对于电话号码来说,事情没那么简单 - 答案取决于您在世界的哪个地方、是否允许使用国际号码、手机的使用情况带编号(例如,在美国,您无法仅根据电话号码判断它是否是手机号码)。在维基百科上查找“电话编号计划”以获取更多信息。

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.

緦唸λ蓇 2024-11-23 06:34:05

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

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

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

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.

救星 2024-11-23 06:34:05

请参阅使用正则表达式验证电子邮件地址(< a href="http://en.wikipedia.org/wiki/The_Code_Project" rel="nofollow noreferrer">代码项目)用于电子邮件验证并参见解析和验证手机号码的最佳实践(Stack ;溢出)用于手机号码验证。

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.

So要识趣 2024-11-23 06:34:05

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

无需逐个字符检查,用户文化受到尊重!

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

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");
    }
歌枕肩 2024-11-23 06:34:05

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

使用 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
}

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
}
懒的傷心 2024-11-23 06:34:05

对于电话号码验证,请在文本框的 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;
}

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文