适用时间验证(错误) [英] Apprioate Time Validation (Error)

查看:114
本文介绍了适用时间验证(错误)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有以下代码对我的textbox1进行了12小时的验证。但是,如果用户键入错误的格式,我只想显示错误,并且只要输入一个数字就不会开始检测格式是否错误。如果这样做有意义。



因此,如果我输入一个数字,而我正在尝试为其中的文本框键入合适的时间,则说它不正确。我希望只要输入例如'12:61'就进行检测,而不是检测到'1'的格式不正确。这很难解释,如果你自己测试一下,你会看到我的意思。



我想知道你是否可以帮我解决这个问题。



So, i have the below code for a 12 hour validation for my textbox1. However i would only like it show the error if the user types the incorrect format in and not start detecting if the format is wrong as soon as one number is typed in. If that makes sense.

So if i type one number in while i am trying to type a suitable time for the textbox in it says it is incorrect. I want the detection to take place as soon as i type for example '12:61' and not detect that '1' is in the incorrect format. This is hard to explain and if you test this for yourself you will see what i mean.

I was wondering if you could help me fix this issue please.

System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^([0-9]|1[0-2]):[0-5]\d(:[0-5]\d(\:\d{1,3})?)?$");
if (regex.IsMatch(Textbox1.Text))
{
    MessageBox.Show("Time is correct.");
}
else
{
    MessageBox.Show("Time is not correct.");
}

推荐答案

);
if (regex.IsMatch(Textbox1.Text))
{
MessageBox.Show( 时间正确。);
}
else
{
MessageBox.Show ( 时间不正确。);
}
"); if (regex.IsMatch(Textbox1.Text)) { MessageBox.Show("Time is correct."); } else { MessageBox.Show("Time is not correct."); }


不要将Regex用于此目的。验证数据,而不仅仅是表示数据的字符串。对于日期/时间,尝试将字符串解析为 System.DateTime ,可能带有指定精确字符串格式和/或文化的参数。这可以通过其中一种方法 System.DateTime.TryParse 或<$ c $来完成c> System.DateTime.TryParseExact :

http://msdn.microsoft.com/en-us/library/system.datetime%28v=vs.110%2 9.aspx [ ^ ]。



格式字符串请参阅:

http://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110) .aspx [ ^ ],

http ://msdn.microsoft.com/en-us/library/8kb3ddd4(v = vs.110).aspx [ ^ ]。



如果解析是成功后,这些函数将返回true,这意味着验证通过。一个副作用,在成功的情况下,你将得到公认的 DateTime 的实例:-)。



-SA
Don't use Regex for this purpose. Validate data, not just strings representing data. For date/time, try to parse string to System.DateTime, possibly with parameters specifying exact string format and/or culture. This can be done by one of the methods System.DateTime.TryParse or System.DateTime.TryParseExact:
http://msdn.microsoft.com/en-us/library/system.datetime%28v=vs.110%29.aspx[^].

For format strings, please see:
http://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx[^],
http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx[^].

If parse is successful, these function will return true, which means the validation is passed. A a side effect, in the case of success, you will get the instance of recognized DateTime :-).

—SA


这篇关于适用时间验证(错误)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆