Reputation: 170
I am having an input on my site allow for people to put their times in and want it to be a stopwatch-style format.
Here is what I have so far: https://jsfiddle.net/k4q3x0hd/3/
$('.time_score').keydown(function(event) {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value.replace(/\D/g, "").replace(/\B(?=(\d{2})+(?!\d))/g, ":");
});
});
What I need it to do is account for if someone puts in 60 (for seconds) it auto formats to 00:60:00.
What are some ways to format this to allow it auto add the 00 Before and after the 60 but still retain the ability for the user to input a full min:sec:mil time set.
I am new to regex and trying to figure out, forgive me if this is an easy fix.
Added for more details:
The users will enter event times for sports and the input would be in a 00:00:00 format (Min:Secs:Miliseconds). If the user completes an event in 60 seconds the score taker my just type 60 instead of 00:60:00, I would like to find a way to check entries so that if they put half it will correct it to adding the 00: in front or pop up a message that explains correct format
Upvotes: 0
Views: 139
Reputation: 1897
If you really want to use regular expressions, try this one: ^(?:\d{2}:){2}\d{2}$
. Technically you could also use ^(?:\d\d:){2}\d\d$
, which I guess is actually 2 characters shorter. Both accomplish the same thing: only "00:00:00" should end up matching that, so if you string doesn't then you can replace it with 00:{user value}:00.
Javascript has a quick way to test a string against a regex: /regex/.test(string)
.
So fully:
var regex = /^(?:\d{2}:){2}\d{2}$/;
$(".time_score").blur(function() {
var value = $(this).val();
if (!regex.test(value)) {
$(this).val("00:" + value + ":00");
}
});
Here's an updated working example: https://jsfiddle.net/k4q3x0hd/16/
From your code, I changed it to on blur just to keep this from firing every time someone enters something in (as yours did with keydown).
Upvotes: 1