时间选择器验证?JQuery/Javascript
我使用时间选择器作为开始和结束时间。我想对这两个输入字段进行验证,以防用户输入错误的时间格式。以下是我的HTML代码:时间选择器验证?JQuery/Javascript,javascript,jquery,regex,timepicker,Javascript,Jquery,Regex,Timepicker,我使用时间选择器作为开始和结束时间。我想对这两个输入字段进行验证,以防用户输入错误的时间格式。以下是我的HTML代码: <th>Start Time:</th> <td> <input type="text" id="stime" name="stime" maxlength="10"/> </td> <th>End Time:</th> <td> <input type="text
<th>Start Time:</th>
<td>
<input type="text" id="stime" name="stime" maxlength="10"/>
</td>
<th>End Time:</th>
<td>
<input type="text" id="etime" name="etime" maxlength="10"/>
</td>
我的代码不工作,如果我在计时器中选择正确的时间格式,我会得到时间错误的警告。如果有人能帮我解决这个问题,请告诉我。我的时间值如下所示:
start time: 08:00 am
end time: 01:15 pm
如果要匹配在
am
和pm
中分割的时间间隔,时间范围将介于00:00
和12:59
之间
因此,您的正则表达式将是:
^(?:(?:0?\d|1[0-2]):[0-5]\d)$
检查
Legenda
^ # Start of the string
(?: # NCG1
(?: # NCG2
0?\d # An optional zero followed by a single number between zero and nine \d is just like [0-9]
| # OR
1[0-2] # A literal '1' followed by a single number between zero and two
) # CLOSE NCG2
: # A literal colon ':'
[0-5]\d # A single number from 0 to 5 followed by any digit
) # CLOSE NCG1
$ # End of the string
Js演示版
var re=/^((?:0?\d|1[0-2]):[0-5]\d)$/;
var测试=['08:00'、'01:15'、'1:14'、'02:23'、'23:23'、'12:01'、'13:05'、'3:04'、'5:65'、'0:0'、'12:9'、'0:34'、'0:01'、'00:31'、'0:00'、'00:00'];
var-m;
while(t=tests.pop()){
document.getElementById(“r”).innerHTML+='“+t+'”
;
document.getElementById(“r”).innerHTML++=“有效时间”+((t.match(re))?“是”:“否”)+”
;
}
什么是“时间选择器”是一个框架/api?您应该提供时间和时间示例值。只需控制台它们并复制有问题的粘贴内容。timepicker是一个api框架。此正则表达式要求24格式的hh:mm:ss-秒是可选的。将您的正则表达式模式切换到/^([0]?[1-9])|(1[0-2]):([0-5]?[0-9])\s([a | p]m$/i,正如我在这里使用的:-注意,我还没有对其进行详尽的测试,但我认为它应该适合你。我认为这个正则表达式有一些问题。它将匹配一位数的分钟数(例如:0:0、12:9均有效)。按照惯例,这通常不是一个被使用的表示。另外,如果您使用的是AM/PM,我不希望0:xx是有效时间。如果你不使用上午/下午,你需要接受13-23小时。
^ # Start of the string
(?: # NCG1
(?: # NCG2
0?\d # An optional zero followed by a single number between zero and nine \d is just like [0-9]
| # OR
1[0-2] # A literal '1' followed by a single number between zero and two
) # CLOSE NCG2
: # A literal colon ':'
[0-5]\d # A single number from 0 to 5 followed by any digit
) # CLOSE NCG1
$ # End of the string