jovan jovan - 1 month ago 7
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:

([01]?[0-9]|2[0-3]):[0-5][0-9]


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

Answer

you can use regex in JavaScript too:

http://www.w3schools.com/jsref/jsref_obj_string.asp

use .search() - http://www.w3schools.com/jsref/jsref_search.asp

or .match() - http://www.w3schools.com/jsref/jsref_match.asp

or .replace() - http://www.w3schools.com/jsref/jsref_replace.asp

EDIT:

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

EDIT2:

here the documentation of regexpobject in javascript:

http://www.w3schools.com/jsref/jsref_obj_regexp.asp

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

EDIT3:

fixed the regexp

Comments