JQuery - checking the correct time format

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

Since the existing client-side validation is in jQuery, I would also like to keep this in jQuery.

I am basically a PHP programmer, so I need help writing this in optimal mode.

I know that I can check every single character (first two = digits, third = ':', last two = digits), but is there any way to do this more elegantly, while checking the number of hours does not exceed 23 and the number of minutes does not exceeds 59?

In PHP, I would use regular expressions, I assume 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.

+3
source share
4 answers

you can also use regex in javascript:

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

using .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's the regexpobject documentation 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:

regular expression fixed

+8

JavaScript /. , ...

var isValidTime = /([01]?[0-9]|2[0-3]):[0-5][0-9]/.test(inputString);

, , 24H HH: mm. , , - true, - . , , ,...

var isValidTime = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(inputString);

, string.match JS.

, , , , jQuery - Javascript - ! jQuery.

+4

JavaScript yourstring.match(regexp), .

RegEx, , .match(), , .

+2

Another approach, but using additional javascript lib instead of regular expressions:

var valid = moment(timeStr, "HH:mm", true).isValid();

I think if you are already using moment.js in your project, there are no flaws.

And since you didn’t specifically request a response using regular expressions, I think this is true.

+1
source

All Articles