JAVASCRIPT

Validate 24-Hour Time Format (HH:MM or HH:MM:SS)

Validate if a string represents a valid 24-hour time (HH:MM or HH:MM:SS) using a precise regular expression for robust input checks.

function isValid24HourTime(timeString) {
    const regex = /^(?:2[0-3]|[01]?[0-9]):(?:[0-5]?[0-9])(?::(?:[0-5]?[0-9]))?$/;
    return regex.test(timeString);
}

// Example usage:
// console.log(isValid24HourTime('14:30'));
// console.log(isValid24HourTime('09:05:22'));
// console.log(isValid24HourTime('25:00'));
// console.log(isValid24HourTime('10:65'));
// console.log(isValid24HourTime('1:2'));
How it works: This JavaScript function validates a string to ensure it adheres to a strict 24-hour time format (HH:MM or HH:MM:SS). The regular expression `^(?:2[0-3]|[01]?[0-9]):(?:[0-5]?[0-9])(?::(?:[0-5]?[0-9]))?$` precisely matches hours from 00-23, minutes from 00-59, and an optional seconds part also from 00-59. The `^` and `$` anchors ensure the entire string must match the pattern, preventing partial matches.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs