jovan jovan - 8 months ago 50
Javascript Question

jQuery - check proper time format

I have an input field where the user enters a time in format mm:hh. The format is specified inside the field (default value 09:00) but I still want to perform a client-side check to see if the format is correct.

Since the existing client-side validation is in jQuery, I'd like to keep this in jQuery as well.

I'm mainly a PHP programmer so I need some help writing this one in an optimal manner.

I know I can check each individual character (first two = digits, third = ':', last two = digits) but is there a way to do it more elegantly, while also checking the hour count is not larger than 23 and the minute count isn't larger than 59?

In PHP I would use regular expressions, I assume there's something similar for jQuery?

Something like this makes sense to me:


But I'm not too familiar with jQuery syntax so I'm not sure what to do with it.


you can use regex in JavaScript too:

use .search() -

or .match() -

or .replace() -


    var regexp = /([01][0-9]|[02][0-3]):[0-5][0-9]/;
    var correct = ($('input').val().search(regexp) >= 0) ? true : false;


here the documentation of regexpobject in javascript:

    var regexp = /([01][0-9]|[02][0-3]):[0-5][0-9]/;
    var correct = regexp.test($('input').val());


fixed the regexp