c# - 这些正则表达式验证和异常有什么问题?
问题描述
这是对旧问题的更新。我正在制作一个 Windows 窗体应用程序来请求联系信息。我创建了一个类来修剪输入文本并检查文本框是否为空。我还为电子邮件和电话号码分配了模式。然而,文本没有遵循正则表达式,也没有捕获任何异常。
表单只有一个按钮,它应该编译并显示插入到文本框中的信息。
我对从文本框中收集的字符串使用了 Get 请求方法。
bool GetPhone(ref string phonenumber)
{
bool success = true;
try
{
txtPhone.Text=Input.TrimText(txtPhone.Text);
if (Input.IsTextEmpty(txtPhone.Text))
throw new InputRequiredException();
phonenumber = txtPhone.Text;
Regex Regphone = new Regex(@"^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$");
Match matchphone = Regphone.Match(phonenumber);
if (matchphone.Success)
success = true;
else throw new InputRequiredException();
}
catch(Exception error)
{
string remediation = "Enter a valid phone number.";
Input.ShowError(error, remediation);
Input.SelectText(txtPhone);
}
try
{
int Phone = Convert.ToInt32(txtPhone.Text);
success = true;
}
catch (Exception error)
{
string remediation = "Enter a valid phone number.";
Input.ShowError(error, remediation);
Input.SelectText(txtPhone);
}
return success;
}
和一堂课。
class Input
{
static public string TrimText(string A)
{
return A.Trim();
}
internal static bool IsTextEmpty(string A)
{
if (string.IsNullOrEmpty(A))
{
return true;
}
else
{
return false;
}
}
internal static void ShowError(object error, string remediation)
{
}
static public void SelectText(TextBox textBox1)
{
textBox1.SelectAll();
}
}
异常类
internal class InputRequiredException : Exception
{
public InputRequiredException()
{
}
public InputRequiredException(string message) : base(message)
{
message = "Invalid Input.";
}
public InputRequiredException(string message, Exception innerException) : base(message, innerException)
{
}
protected InputRequiredException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
代码中没有显示错误,程序运行顺利,但我没有得到所需的输出。我需要的是电话号码文本框来验证输入并在输入错误时抛出异常。目前,文本框接受任何和所有值,没有任何例外。在编码方面,我完全是个菜鸟,并且理解代码可能存在逻辑错误。无论是一个错误还是多个错误,或者代码只是未完成,请随时告诉我。
解决方案
欢迎来到 SO。我想知道您和用户是否简单地要求与电话号码关联的 10 个号码而不是特定格式的相同 10 个号码?
例如,一位用户可能会给您 5559140200,而另一位用户可能会给您 (555) 914-0200。也许格式只是微不足道,可以忽略,让您可以简单地检查数字序列,而不是关注可能存在或不存在的格式?这样,您既可以将文本框限制为仅限数字输入,也可以限制为最少和最多 10 个字符。
如果您希望标准化数据库条目的输入或与标准化的数据库记录进行比较,您可以采用他们的 10 数字序列,在提供之后对其进行格式化,然后记录或比较。这样,您和您的用户都不会受到输入刚性的约束,您可以在按下回车键后应用它......
String.Format("{0:(###)###-####}", 5559140200);
...在没有正则表达式的情况下有效地达到 (555)914-0200 的目标。
如果这不是您的目标,也许是不同的正则表达式模式......
Regex Regphone = new Regex(@"\([0-9]{3}\)[0-9]{3}\-[0-9]{4}");
根据评论中的要求,以下是减轻抛出异常的 String.Format() 路由的示例...
using System;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace phone_number_sanitizer
{
public partial class Form1 : Form
{
#region Variables
string phonenumber = "";
string[] msg = new string[] { "Enter a valid phone number.", "Other messages you may wish to include." }; // referenced by array index
#endregion
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
#region UI Setup
txtPhone.MaxLength = 10;
btnSubmit.Enabled = false;
#endregion
}
private void txtPhone_TextChanged(object sender, EventArgs e)
{
/*
txtPhone's MaxLength is set to 10 and a minimum of 10 characters, restricted to numbers, is
required to enable the Submit button. If user attempts to paste anything other than a numerical
sequence, user will be presented with a predetermined error message.
*/
if (txtPhone.Text.Length == 10) { btnSubmit.Enabled = true; } else { btnSubmit.Enabled = false; }
if (Regex.IsMatch(txtPhone.Text, @"[^0-9]"))
{
DialogResult result = MessageBox.Show(msg[0], "System Alert", MessageBoxButtons.OK);
if (result == DialogResult.OK)
{
txtPhone.Text = "";
txtPhone.Focus();
btnSubmit.Enabled = false;
}
}
}
private void txtPhone_KeyPress(object sender, KeyPressEventArgs e)
{
/*
Here, you check to ensure that an approved key has been pressed. If not, you don't add that character
to txtPhone, you simply ignore it.
*/
if (Regex.IsMatch(e.KeyChar.ToString(), @"[^0-9]") && e.KeyChar != (char)Keys.Back) { e.Handled = true; }
}
private void btnSubmit_Click(object sender, EventArgs e)
{
/*
By this phase, the Submit button could only be enabled if user provides a 10-digit sequence. You will have no
more and no less than 10 numbers to format however you need to.
*/
try
{
phonenumber = String.Format("{0:(###)###-####}", txtPhone.Text);
}
catch { }
}
}
}
直接在文本框中控制数字序列的输入与自动格式化的组合如下:
using System;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace phone_number_sanitizer
{
public partial class Form1 : Form
{
#region Variables
string phonenumber = "";
string[] msg = new string[] { "Enter a valid phone number.", "Other messages you may wish to include." };
#endregion
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
#region UI Setup
txtPhone.MaxLength = 13;
btnSubmit.Enabled = false;
#endregion
}
private void txtPhone_TextChanged(object sender, EventArgs e)
{
if (txtPhone.Text.Length == 10 && Regex.IsMatch(txtPhone.Text, @"[0-9]")
{
btnSubmit.Enabled = true;
txtPhone.Text = txtPhone.Text.Insert(6, "-").Insert(3, ")").Insert(0, "(");
txtPhone.SelectionStart = txtPhone.Text.Length;
txtPhone.SelectionLength = 0;
}
else if (txtPhone.Text.Length == 13 && Regex.IsMatch(txtPhone.Text, @"\([0-9]{3}\)[0-9]{3}\-[0-9]{4}"))
{
btnSubmit.Enabled = true;
}
else
{
btnSubmit.Enabled = false;
txtPhone.Text = txtPhone.Text.Replace("(", "").Replace(")", "").Replace("-", "");
txtPhone.SelectionStart = txtPhone.Text.Length;
txtPhone.SelectionLength = 0;
}
}
private void txtPhone_KeyPress(object sender, KeyPressEventArgs e)
{
if (Regex.IsMatch(e.KeyChar.ToString(), @"[^0-9]") && e.KeyChar != (char)Keys.Back) { e.Handled = true; }
}
private void btnSubmit_Click(object sender, EventArgs e)
{
try
{
phonenumber = txtPhone.Text;
}
catch { /* There's nothing to catch here so the try / catch is useless. */}
}
}
}
它稍微复杂一点,您可以完全摆脱文本框的需求,而无需依赖用户将其提供给您。使用这种替代方法,您的用户可以选择键入他们的 10 位电话号码并动态完成格式化,或者他们可以粘贴相应格式化的号码,即“(555)941-0200”。任一选项都将启用提交按钮。
提供这两个选项是为了让您能够控制输入。有时消除输入错误的可能性比在发生错误时弹出错误消息更好。有了这些,除了原始的 10 位数字序列或格式化的 10 位电话号码之外,用户将无法为您提供任何东西,而您得到的正是您想要的,没有任何麻烦。
推荐阅读
- vb.net - Vb.net 试图关闭在面板中打开的表单。但是在关闭它时,父级会完全关闭/隐藏
- oracle - 表情符号字符破坏 Apex HTTP 引擎?
- python - Mayavi:如何翻转场景的 Z 轴?
- java - 测试Ng | 编译器总是跳过 @Test(dataprovider) 注释
- sql - 如何仅更新 SQL Server 中的 MAX 列
- python - Django 表单向导:为什么提交后没有调用 done() 方法?
- c# - System.IO.IOException:参数不正确。当 Console.OutputEncoding = Encoding.GetEncoding("GB2312");
- python - 给定包含 Python 的列表,查找项目索引的最快方法是什么?
- c# - WPF 在 ViewModel 中调用动画
- ios - CosmicMind/Material : 如何在 iOS 中更改 CheckButton 选定颜色