如何在Windows应用程序中限制或过滤Mask TextBox中的输入

时间:2014-09-24 07:18:30

标签: c# datetime windows-applications maskedtextbox

更新:编辑我的问题以便更好地理解我希望

我将Mask TextBox属性设置为短MM/DD/YYYY00/00/0000但是它可以接受超过12个月且超过31的日期。如何仅将月份过滤到12并且仅限日期到31?

2 个答案:

答案 0 :(得分:0)

^([012]\d|30|31)/(0\d|10|11|12)/\d{4}$

在重写的控件中使用上面的正则表达式。

答案 1 :(得分:0)

尝试解决这个问题,所以在这里。我的输入用户的生日月份不能高于12,年份必须小于今天(尚未解决如何接受当年。

        private void Form1_Load(object sender, EventArgs e)
    {
        maskedTextBox1.Mask = "00/00/0000";
        maskedTextBox1.ValidatingType = typeof(System.DateTime);
        maskedTextBox1.TypeValidationCompleted += new TypeValidationEventHandler(maskedTextBox1_TypeValidationCompleted);


    }

    void maskedTextBox1_TypeValidationCompleted(object sender, TypeValidationEventArgs e)
    {
        if (!e.IsValidInput)
        {
            MessageBox.Show("The data you supplied must be a valid date in the format mm/dd/yyyy.");
        }
        else
        {

            DateTime userDate = (DateTime)e.ReturnValue;
            if (userDate >= DateTime.Now)
            {

                MessageBox.Show("The date in this field must be less or equal than today's date.");
                e.Cancel = true;
            }
        }
    }
相关问题