从<输入类型= " time "…>验证时间

Validate a time from the <input type=“time”…>

本文关键字:验证 time 时间 输入 类型      更新时间:2023-09-26

我想验证输入类型为时间的字段。目前,我正在尝试使用javascript方法来验证字段。

这是我使用的代码。

我当前的时间格式是:12:00 pm

只是想知道我如何验证输入类型的时间字段。我不确定如何在验证上实现。我希望我能得到一些关于如何验证它的提示。

验证时间格式/值/输入的最简单方法是添加一个事件侦听器。可以在change事件上,也可以在将数据提交给服务器之前。一个简单的正则表达式就足够了:

var timeVal = document.querySelector('#timeInput').value;
if (timeVal.match(/'d+:'d+/))
    console.log(timeVal + ' is a valid time-format');
else
    return false;//or preventDefault + stopPropagation() on event
<标题>例子h1> 注:
time输入类型还没有得到普遍支持,远远不够。如果您使用各种插件,或者使用一些选择,并使用JS处理它们的值会更好。

document.querySelector('#check').addEventListener('click', function()
{
document.getElementById("foobar").style.border = "solid 1px #ccc";
if(checkValid()){
  alert('OK');
}else{
  //alert('Invalid');
document.getElementById("foobar").style.border = "solid 1px red";  
}
    
}, false);
function checkValid(){
var timeVal = document.querySelector('#foobar').value;
if (timeVal.match(/'d+:'d+/))
   return true;
else
    return false;
}
<input type='time' id='foobar'>
    <input type='button' value='test' id='check'>

你希望用户输入时间还是什么?我的意思是,通常在时间和日期方面,最好使用组件。无论如何,javascript是最好的工具,但我认为你可以使用javascript中的RegExp作为一个很好的解决方案