Validate Time of user input

Advertisements

I need to write a function to validate the time of user input from console. The format of the time is HH:mm in 24 hours time.

function isValidTime(timeString) {
    var regex_time = /^\d{2}\:\d{2}$/;

    if(!regex_time.test(timeString))
    {
        return false;
    }

    var hour = timeString.getHour();
    var minute = timeString.getMinutes();

    if ((hour > 0 && hour <= 23) && (minute > 0 && minute <= 59)) {
        return true;
    }

}

This is the code I have so far. When I input 5:01, the output is invalid format. When I input 17:01, it shows

node:internal/readline/emitKeypressEvents:71
            throw err;
            ^

TypeError: timeString.getHour is not a function

Could you please help with this function, I am reading user input with readline.

>Solution :

I suggest you use capture groups in the regular expression… And the match method.

Match will return null if no match at all
or an array containing the full match at position 0 followed by all capture group results.

function isValidTime(timeString) {
    const regex_time = /^(\d{2})\:(\d{2})$/;  // Use capture groups

    const timeMatches = timeString.match(regex_time)
    if(!timeMatches){
      return false
    }
    const hour = parseInt(timeMatches[1])
    const minute = parseInt(timeMatches[2])

    if ((hour >= 0 && hour <= 23) && (minute >= 0 && minute <= 59)) {
        return true;
    }
    return false
}

console.log(isValidTime("5:01"))  // false

console.log(isValidTime("17:05"))  // true

Leave a ReplyCancel reply