user759235
user759235

Reputation: 2207

Validate a time string (up to one hour) with javascript

I am looking for a regex pattern to validate a string and see if this is an valid time. It can only be up to one hour. I want to check if a string is a valid time or return false.

It needs to be in mm:ss format

Good = 00:00
Good = 60:00
Bad  = 60:01
Bad  = 89:09
Bad  = 3445

Upvotes: 1

Views: 87

Answers (2)

Johan
Johan

Reputation: 35194

My shot at it:

function validate(input){
    var split = input.split(':'), // split the input
        part1 = +split[0], part2 = +split[1]; // try to parse parts to numbers
    if(!part1 || !part2) return false; // didn't get 2 valid numbers
    return (part1*60 + part2) < 3600; // check if they're less then 1 hour
}

console.log(validate('55:09')); // true
console.log(validate('61:09')); // false
console.log(validate('6155')); // false

http://jsfiddle.net/LGheT/

Upvotes: 1

fejese
fejese

Reputation: 4628

Using regex to validate number ranges is not an optimal solution. You need to create a quite long pattern to evaluate easy conditions. You'd be probably better of checking only if it's a number:number pattern then split it and check if the parts are consistent with your requirements or not:

function checkTime(time) {
    if (time.match("^[0-9]{2}:[0-9]{2}$") === null) {
        return false;
    }
    var parts = time.split(':');
    if (parts[0] > 60) {
        return false;
    }
    if (parts[0] == 60 && parts[1] > 0) {
        return false;
    }
    return true;
}

That being said you can create a regex for this if you really want:

function checkTime(time) {
    return time.match("^(60:00|[0-5][0-9]:[0-5][0-9])$") !== null;
}

It's just much harder to maintain and read this kind of code later on.

Upvotes: 1

Related Questions