最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Validate a HH:MM time - Stack Overflow

programmeradmin2浏览0评论

This is my javascript sample. How can it be improvised?

function a(id) 
{
    var n=document.getElementById(id);
    var re=/^[0-9]:[0-9] [to] [0-9]:[0-9]*$/;

    if(re.test(n.value))
    {
        n.style.backgroundColor="#52F40C";
    }
    else
    {
        window.alert("Invalid Entry");
        n.style.backgroundColor="#F40C0C";
        n.focus();
        n.value="";
    }
}

I wanna validate user input which should be for example 10:30 to 12:30. I'm a fresher please suggest me.

This is my javascript sample. How can it be improvised?

function a(id) 
{
    var n=document.getElementById(id);
    var re=/^[0-9]:[0-9] [to] [0-9]:[0-9]*$/;

    if(re.test(n.value))
    {
        n.style.backgroundColor="#52F40C";
    }
    else
    {
        window.alert("Invalid Entry");
        n.style.backgroundColor="#F40C0C";
        n.focus();
        n.value="";
    }
}

I wanna validate user input which should be for example 10:30 to 12:30. I'm a fresher please suggest me.

Share Improve this question edited Jan 14, 2021 at 10:54 Roko C. Buljan 206k41 gold badges327 silver badges335 bronze badges asked Jan 23, 2013 at 4:48 suhassuhas 1273 gold badges3 silver badges11 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 12

Use this regex for time format hh:mm

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

I have just placed the time format.Try to edit this for your requirement.

I believe, this is what you're looking for:

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

You can check it here: here

To check whether a string matches a 24h format (range 00:00 → 23:59) use RegExp.prototype.test()

// Validate "hh:mm" format
const validHHMMstring = (str) => /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(str);

console.log(validHHMMstring("99:99")); // false
console.log(validHHMMstring("24:00")); // false
console.log(validHHMMstring("23:60")); // false
console.log(validHHMMstring("23:59")); // true
console.log(validHHMMstring("00:00")); // true

Use Like:

// Having i.e: <input name="time">
const time = document.querySelector("[name=time]").value.trim();
if (validHHMMstring(time)) {
  // do something, is valid HH:MM
}
发布评论

评论列表(0)

  1. 暂无评论