Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Validate Time of user input

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading