valid time javascript

What is Valid Time Javascript?

Valid Time Javascript is used to validate user input time format in HTML forms. It checks whether the entered time is in a valid format or not. The valid time format can be in 12-hour or 24-hour format.

How to Implement Valid Time Javascript?

We can implement Valid Time Javascript using the following steps:

  1. Create an HTML form with an input field for time.
  2. Define a function to validate the entered time.
  3. Call the function on form submission.

Here is an example of Valid Time Javascript:

function validateTime(inputTime) {
    var timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
    return timeRegex.test(inputTime);

The above Javascript function checks whether the input time matches the required format or not. It uses a regular expression to match the pattern of valid time format.

To use the above function, call it on form submission event:

document.querySelector('form').addEventListener('submit', function(e) {
    e.preventDefault(); // prevent form submission
    var inputTime = document.querySelector('#time-input').value;
    if(validateTime(inputTime)) {
        alert('Valid Time Format');
    } else {
        alert('Invalid Time Format');

In the above code, we prevent the default form submission event and get the input value from the time input field. Then we call the validateTime() function on this input value to check whether it matches the valid time format or not. Finally, we show an alert message based on the validation result.

Alternative Ways to Implement Valid Time Javascript

There are other ways to implement Valid Time Javascript as well. One of them is by using regular expressions directly in the HTML pattern attribute:

<input type="time" pattern="^([01]?[0-9]|2[0-3]):[0-5][0-9]$" required>

In the above code, we define the HTML pattern attribute with the required regular expression pattern for valid time format. This will automatically validate the input time format when the form is submitted.

Another way to implement Valid Time Javascript is by using a third-party library like jQuery Validation:

// Include jQuery and jQuery Validation scripts in your HTML file
// Then add the following code in your Javascript file

    rules: {
        time-input: {
            required: true,
            pattern: /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/
    messages: {
        time-input: {
            required: 'Please enter a valid time',
            pattern: 'Invalid time format'

In the above code, we use jQuery Validation plugin to validate the time input field. We define rules and error messages for the input field. This is a more convenient way to implement Valid Time Javascript in larger projects.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]