我是 C#.net 的新手。我想要验证仅采用 hh:mm:ss 格式的文本框。
下面是我的代码及其工作原理。它给出的输出为 true 23:45:45(仅作为示例),对于 -23:45:45 也为 true(仅作为示例)。
现在我想要验证 -23:45:45 返回 false (仅示例),因为它是负时间。我的运行代码在负时间内不起作用。
IsTrue = ValidateTime(txtTime.Text);
if (!IsTrue)
{
strErrorMsg += "\nPlease insert valid alpha time in hh:mm:ss formats";
isValidate = false;
}
public bool ValidateTime(string time)
{
try
{
Regex regExp = new Regex(@"(([0-1][0-9])|([2][0-3])):([0-5][0-9]):([0-5][0-9])");
return regExp.IsMatch(time);
}
catch (Exception ex)
{
throw ex;
}
}
我根本不会使用正则表达式 - 我只是尝试将结果解析为DateTime
使用自定义格式:
public bool ValidateTime(string time)
{
DateTime ignored;
return DateTime.TryParseExact(time, "HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out ignored);
}
(If you really想要坚持使用正则表达式,请遵循 Mels 的答案。我会摆脱毫无意义的 try/catch 块,并且可能只构建一次正则表达式并重用它。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)