这是对较旧问题的更新。我正在制作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)
{
}
}
代码中没有显示任何错误,程序运行流畅,但是我没有得到想要的输出。我需要的是电话号码文本框,以验证输入并在输入错误的情况下引发异常。当前,该文本框正在接受任何和所有值,没有任何例外。在编码方面,我是一个绝对的菜鸟,并且了解代码可能存在逻辑错误。无论是一个错误还是多个错误,或者代码只是未完成,请随时让我知道。
答案 0 :(得分:0)
欢迎来到SO。我想知道对于您和用户来说,仅要求与电话号码关联的10个数字,而不是特定格式的相同10个数字,会不会更简单?
例如,一个用户可能给您5559140200,而另一个用户可能给您(555)914-0200。也许格式只是微不足道的,可以忽略不计,使您有更多时间去检查数字序列,而不是着眼于可能存在或不存在哪种格式?这样,您既可以将文本框限制为仅数字输入,也可以限制为最多10个字符。
如果您希望标准化输入以用于数据库输入或与标准化的数据库记录进行比较,则可以采用10位数的序列,在提供序列号后对其进行格式化,然后进行记录或比较。这样,您和您的用户都不会受到输入刚性的限制,您只需在按下Enter键之后就可以应用它。
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位电话号码之外,用户将无法为您提供任何其他服务,而您所得到的正是您想要的而没有任何麻烦。