如何使用 Javascript 验证带有小时和分钟的输入文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5563028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:50:11  来源:igfitidea点击:

How to validate with Javascript an Input text with Hours and Minutes

javascriptvalidation

提问by systempuntoout

I have to build an HTML Form with an Input text field for Hours and Minutes.
Something like:

我必须构建一个带有小时和分钟输入文本字段的 HTML 表单。
就像是:

Name :[Foo]
Surname :[Bar]
Task :[Spam]
Hours Minutes :[00:15] <-- Input text.

姓名:[Foo]
姓氏:[Bar]
任务:[垃圾邮件]
小时分钟:[00:15] <-- 输入文本。

How can I help/validate/force user to compile Hours and Minutes values in the only allowed HH:mmformat using Javascript? *

我如何帮助/验证/强制用户使用 Javascript以唯一允许的HH:mm格式编译小时和分钟值?*

Valid time range: from 00:00to 23:59

有效时间范围:从00:0023:59

* I can't use Jquery and of course I will double check the submitted value server side

* 我不能使用 Jquery,当然我会仔细检查提交的值服务器端

回答by dominicbri7

Either with the following regular expression :

使用以下正则表达式:

^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?$

Or by hand, but I strongly suggest the RegExp :) A simple example :

或者手动,但我强烈建议使用 RegExp :) 一个简单的例子:

<SCRIPT TYPE="text/JavaScript">
    function validateHhMm(inputField) {
        var isValid = /^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?$/.test(inputField.value);

        if (isValid) {
            inputField.style.backgroundColor = '#bfa';
        } else {
            inputField.style.backgroundColor = '#fba';
        }

        return isValid;
    }
</SCRIPT>
<FORM METHOD="POST">
    <input type="text" onchange="validateHhMm(this);" />
</FORM>

回答by TRT 1968

The RegExp from the first answer doesn't match the OP's query correctly.

第一个答案中的 RegExp 与 OP 的查询不正确。

^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?$

Should be

应该

^([0-1][0-9]|2[0-3]):([0-5][0-9])$

Matches 00-19 or 20-23 : 00-59

匹配 00-19 或 20-23 : 00-59

OP requested validation of HH:MM in the range 00:00 - 23:59

OP 请求在 00:00 - 23:59 范围内验证 HH:MM

No seconds. 24:00 should not be valid. Double digits for input of hour and minute.

没有秒。24:00 应该无效。输入小时和分钟的两位数。

回答by Mouadh

<HTML>
<Head>
<script language="javascript">
function validateTime(obj)
{
    var timeValue = obj.value;
    if(timeValue == "" || timeValue.indexOf(":")<0)
    {
        alert("Invalid Time format");
        return false;
    }
    else
    {
        var sHours = timeValue.split(':')[0];
        var sMinutes = timeValue.split(':')[1];

        if(sHours == "" || isNaN(sHours) || parseInt(sHours)>23)
        {
            alert("Invalid Time format");
            return false;
        }
        else if(parseInt(sHours) == 0)
            sHours = "00";
        else if (sHours <10)
            sHours = "0"+sHours;

        if(sMinutes == "" || isNaN(sMinutes) || parseInt(sMinutes)>59)
        {
            alert("Invalid Time format");
            return false;
        }
        else if(parseInt(sMinutes) == 0)
            sMinutes = "00";
        else if (sMinutes <10)
            sMinutes = "0"+sMinutes;    

        obj.value = sHours + ":" + sMinutes;        
    }

    return true;    
}


</script>
</Head>
<Body>
<input type="text" onblur="validateTime(this)">
</Body>
</HTML>

回答by KooiInc

How about

怎么样

function validTime(inputStr) {
    if (!inputStr || inputStr.length<1) {return false;}
    var time = inputStr.split(':');
    return time.length === 2 
           && parseInt(time[0],10)>=0 
           && parseInt(time[0],10)<=23 
           && parseInt(time[1],10)>=0 
           && parseInt(time[1],10)<=59;
}

回答by VeroLom

You can use something like jQuery.maskedit

你可以使用类似 jQuery.maskedit 的东西

回答by Ali Hallaji

You can use this function to check for time format:

您可以使用此函数检查时间格式:

function validateTime (time) {
  const timeReg = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/
  return time.match(timeReg)
}

If you want to have just hour and minute please replace timeRegwith this:

如果您只想使用小时和分钟,请替换timeReg为:

const timeReg = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/

And this one for the date format:

这是日期格式的:

function validateDate (date) {
  try {
    new Date(date).toISOString()
    return true
  } catch (e) {
    return false
  }
}

回答by Kkkk Kkkk

With moment.js the way is:

使用 moment.js 的方法是:

const time = '23:59'
moment(time, 'HH:mm', true).isValid()

回答by Lomi Faith

might not be the best but this works for me. i am returning false if there is no error in this case. checks for both format and values.

可能不是最好的,但这对我有用。如果在这种情况下没有错误,我将返回 false。检查格式和值。

if (value.substr(2,1) === ':') {
    if (!value.match(/^\d\d:\d\d/)) {
        return "Invalid Format";
    }
    else if (parseInt(value.substr(0,2)) >= 24 || parseInt(value.substr(3,2)) >= 60)  {
        return "Invalid Format";
    }
    else {
        return false;
    }

}
else {
    return "Invalid Format";
}