Winform之TextBox输入日期格式验证yyyy-mm-dd

复制代码 代码如下:

private void button1_Click(object sender, EventArgs e)
        {
            string s = textBox1.Text.ToString();
            bool b = ValidateDataTime(s);
            string rs = "";
            if (b)
            {
                rs = "true";
            }
            else
            {
                rs = "false";
            }
            MessageBox.Show(rs);
        }

        //验证方法-格式为:YYYY-MM-DD
        public static bool ValidateDataTime(string InputStr)
        {
            if (InputStr.Length >0)
            {
                if(Regex.IsMatch(InputStr.Trim(),@"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$"))
                {
                    return true;
                }
                else
                {
                    return false;
                }

            }
            return false;
        }


 

判断YYYY-MM-DD这种格式的,基本上把闰年和2月等的情况都考虑进去了
^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$  

下面的是加了时间验证的  

^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))   (20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d$ 

你可能感兴趣的:(Winform之TextBox输入日期格式验证yyyy-mm-dd)