这是对旧问题的更新。我正在制作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)
{
}
}
代码中没有显示错误,程序运行顺利,但我没有得到所需的输出。我需要的是电话号码文本框以验证输入并在错误的情况下抛出异常。当前,文本框正在接受任何和所有值,没有任何例外。当涉及编码并了解代码可能会有逻辑错误时,我是一个菜鸟。无论是一个错误还是多个错误,或者是否只是未完成的代码,请随时让我知道。
欢迎来到这样。我想知道您和用户只需要与电话号码关联的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位电话号码,用户无法为您提供其他任何东西,而您得到的完全是您想要的,而没有任何麻烦。