【问题标题】:Validation of textbox input in C#在 C# 中验证文本框输入
【发布时间】:2011-06-17 06:49:35
【问题描述】:

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

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

我正在使用 Windows 窗体。

【问题讨论】:

  • 这是一个 asp.net 应用程序、一个 windows 窗体应用程序还是什么?
  • 您使用什么客户端技术? Winforms、ASP.Net、WPF、...?
  • @Paolo Tedesco:这是一个 WINFORM 应用程序
  • @Rewinder : 这是一个 WINFORM 应用程序

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


【解决方案1】:

你可以使用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 的更多详细信息。

【讨论】:

  • 你能给我解释一下吗--" \b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4 }\b" ---------这是允许什么,什么不允许?什么是\b
【解决方案2】:
//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();
}

【讨论】:

    【解决方案3】:

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

    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

    对于电话号码,这并不是那么简单 - 答案取决于您在世界的哪个地方、您是否允许使用国际号码、手机的编号方式(例如,在美国,您无法从单独的电话号码,无论它是否是手机号码)。在 Wikipedia 上查找“电话号码计划”以获取更多信息。

    【讨论】:

      【解决方案4】:

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

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

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

      【讨论】:

        【解决方案5】:

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

        【讨论】:

          【解决方案6】:

          我按照下面的代码所示的方式进行数字验证。

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

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

          【讨论】:

            【解决方案7】:

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

            为正则表达式使用 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
            }
            

            【讨论】:

              【解决方案8】:

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

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2015-11-09
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多