繁体   English   中英

这些正则表达式验证和异常怎么了?

[英]Whats wrong with these regex validation and exceptions?

这是对旧问题的更新。 我正在制作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位数的序列,在提供序列号后对其进行格式化,然后进行记录或比较。 这样,您和您的用户都不会受到输入刚性的约束,您只需在按下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位电话号码之外,用户将无法为您提供任何其他服务,而您所得到的正是您想要的而没有任何麻烦。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM