简体   繁体   English

html5使用模式的时间验证问题

[英]html5 time validation issue using pattern

I am using the HTML5 in build validation but for Time, i am sing the following code The code is pretty simple as it is just checking the format of the time, i am not sure what i am doing wrong here 我在构建验证中使用HTML5,但是对于Time,我正在使用以下代码该代码非常简单,因为它只是检查时间的格式,我不确定在这里我做错了什么

<input name="taskStartTime" type="text" value="05:15 PM" placeholder="Enter a valid start time." size="10" pattern="/^\d{1,2}:\d{2}([ap]m)?$/" title="Enter Valid Time">

But it is not validating and it says invalid time, i think my regex is right, but not sure what is going on here... 但这并没有验证,它说的是无效时间,我认为我的正则表达式是正确的,但不确定这里发生了什么...

Remove the forward slashes: they are part of JavaScript regex literal syntax, not part of general regex syntax. 删除正斜杠:它们是JavaScript regex文字语法的一部分,而不是常规regex语法的一部分。 You don't really need the ^ and $ either because for an input element pattern they are implied. 您实际上并不需要^$ ,因为对于输入元素模式而言,它们是隐含的。

The value you are setting in your example, 05:15 PM won't match your regex either, because it has a space in it and because the "PM" is in capitals. 您在示例中设置的值( 05:15 PM也不会与您的正则表达式匹配,因为其中有空格并且“ PM”用大写字母表示。 To allow for that: 为此:

pattern="\d{1,2}:\d{2}( ?[apAP][mM])?"

Note that for html5 input pattern attributes you can't set the i case insensitive flag that JavaScript (and some other regex implementations) allow. 注意,对于HTML5的输入pattern属性,你可以不设置i不区分大小写标志的JavaScript(和一些其他的正则表达式实现)允许。 According to the specification it does use the JS syntax for the pattern itself, but "it is compiled "with the global, ignoreCase, and multiline flags disabled". 根据规范,它确实对模式本身使用了JS语法,但是“它是在禁用了global,ignoreCase和multiline标志的情况下编译的”。

尝试这个

 <input name="taskStartTime" type="text" value="05:15 PM" placeholder="Enter a valid start time." size="10" pattern="^\\d{1,2}:\\d{2}\\s([AP]M)?$" title="Enter Valid Time"> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM