验证<input type =“time”...>的时间

I would like to validate the field for the input type of time. Currently, I am trying to use the javascript method to validate the field(s).

This is the code that I have used.

My current time format is example: 12:00 pm

Just wondering on how I can validate the fields for the input type of time. I am not sure on how to achieve on the validation. I was hoping if I can get some tips on how to validate it.

Do you expect from user to type the time or what?!i mean usually in time and date stuff it`s better to use components.any way javascript is best tool for such a thing but i think you could use RegExp in javascript as a good solution

The simplest way to validate the time format/value/input would be to add an event listener. Either on the change event, or before submitting the data to the server. A simple regex would be more than enough:

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

example here

Side-note:
the time input-type is not universally supported yet, far from it. It'd be better if you use a plugin of sorts, or use some selects, and process their values using 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'>

</div>