验证 hh:mm:ss [英] Validation for hh:mm:ss

查看:30
本文介绍了验证 hh:mm:ss的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C#.net 的新手.我想要对仅采用 hh:mm:ss 格式的文本框进行验证.下面是我的代码及其工作.它给出了输出 true 23:45:45(仅示例)和 -23:45:45(仅示例)的输出.现在我想要验证对于 -23:45:45(仅示例)返回 false,因为它是负时间.我的运行代码在负时间内不起作用.

I am new in C#.net. I want a validation for textbox which take only hh:mm:ss format. Below is my code and its wroking. It gives output true 23:45:45 (example only) and also true for -23:45:45 (example only). Now I want validation which return false for -23:45:45 (example only) because it is negative time. My running code does not work for negative time.

          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:

I wouldn't use regular expressions at all - I'd simply try to parse the result as a DateTime with a custom format:

public bool ValidateTime(string time)
{
    DateTime ignored;
    return DateTime.TryParseExact(time, "HH:mm:ss",
                                  CultureInfo.InvariantCulture, 
                                  DateTimeStyles.None,
                                  out ignored);
}

(如果您真的想坚持使用正则表达式,请遵循 Mels 的答案.我会摆脱毫无意义的 try/catch 块,并且可能只构建一次正则表达式并重用它也是.)

(If you really want to stick with regular expressions, follow the answer from Mels. And I'd get rid of the pointless try/catch block, and probably just construct the regex once and reuse it, too.)

这篇关于验证 hh:mm:ss的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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