suhas
suhas

Reputation: 127

Validate a HH:MM time

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.

Upvotes: 6

Views: 13832

Answers (3)

Roko C. Buljan
Roko C. Buljan

Reputation: 206121

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
}

Upvotes: 2

IlyaDoroshin
IlyaDoroshin

Reputation: 4699

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

Upvotes: 2

Techy
Techy

Reputation: 2654

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.

Upvotes: 12

Related Questions