【问题标题】:JavaScript regular expression to check time format用于检查时间格式的 JavaScript 正则表达式
【发布时间】:2012-06-19 08:46:06
【问题描述】:

我想要一个在输入不正确时清除 HTML 字段的正则表达式。我创建了这个,但不是在不正确时清除该字段,而是仅在输入 正确时才清除它。

onchange="this.value=this.value.replace(/^([01]?[0-9]|2[0-3]):[0-5][0-9]/,'')"

我尝试“反转”代码,但到目前为止没有成功。

【问题讨论】:

    标签: javascript regex time onchange


    【解决方案1】:
    onchange="this.value=
    /^([01]?[0-9]|2[0-3]):[0-5][0-9]/.test(this.value) ? this.value : ''"
    

    【讨论】:

    • test()的语法错误(对象和参数需要交换),问题代码中还有一个不必要的''参数。
    • 它在 fiddle 中运行,但在独立网页中,与 fiddle 崩溃时使用的代码相同。我在 FF、Chrome 和 IE9 中对其进行了测试。字符串对象没有 test() 方法,正则表达式对象有。在 Firebug 中,我收到错误:value.test is not a function.
    【解决方案2】:
    onchange="if (!this.value.match(/^([01]?[0-9]|2[0-3]):[0-5][0-9]/)) this.value = '';"
    

    【讨论】:

      【解决方案3】:
      if(!/^([01]?[0-9]|2[0-3]):[0-5][0-9]/.test(this.value)) this.value="";
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-29
        • 1970-01-01
        • 2012-07-27
        • 2019-11-05
        • 2014-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多