Checking variable length time with JavaScript Regular Expression

My specific requirement is to validate a string ranging from 1 to 4 characters in length (where H stands for hour and M represents minutes):

If the string has 1 character, it should be in the format of H (a digit between 0-9).

A 2-character string should look like HH (the first H can be between 0-2 and the second one between 0-9; however, if the first H is 2, the second one can only be 0-4).

For a 3-character string, the format should be HMM (first H: between 0-9, first M: between 0-5, second M: between 0-9).

A 4-character string should have the format HHMM (first H: between 0-2, second H: between 0-9; but when the first H is 2, the second H can only be 0-4. Additionally, first M: between 0-5, and second M: between 0-9).

The challenge here lies in not knowing the length of the string beforehand and the same number signifying different things depending on its length. Any suggestions on using JavaScript Regular Expressions to handle this validation?

Answer №1

If you're looking to validate 24-hour time formats using a regular expression, consider the following pattern:

^(2[0-3]|[01]?\d)([0-5]\d)?$

This breakdown helps you understand each segment of the regex:

^                   marks the beginning of the string
2[0-3]              matches 20-23 as valid hours
|                   or
[01]?\d             covers hours 00-19
([0-5]\d)?          includes minutes from 00-59, optional
$                   signifies the end of the string

Note: If you prefer to stick with the more common 0-23 hour range, adjust the regex accordingly.

^(2[0-4]|[01]?\d)([0-5]\d)?$

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript: XHR struggles with managing multiple asynchronous requests

Hey there, I'm currently attempting to access a single resource multiple times with various parameters. Here's what I have so far: Essentially, I am making requests for the following domains: var domains = [ 'host1', 'host2&apos ...

Adding JSON data to an array in Node.JS

I am facing an issue where my JSON data is successfully being appended to an array inside a JSON file. However, the problem is that it is not appending inside of the brackets in the JSON file. Below is the code snippet for my NODE if (req.method == &apo ...

Ionic 5 page div within ion-contents element is experiencing scrolling issues on iPhone devices

My application features a div element containing an ion-slides component. The ion-slides component houses several ion-slide elements that slide horizontally. Here is the relevant code snippet: <ion-content [scrollEvents]="true"> <div ...

Updating a MongoDB subarray with $set now includes adding a new entry rather than just updating existing ones

When trying to update an object in a sub-array, instead of replacing and updating the data, it adds a new entry. Here is the code from controller.js: const updateSubCategory = asyncHandler(async (req, res) => { const { dataArray } = req.body ...

Are there any methods for simultaneously hosting both React and vanilla JavaScript websites?

I want to host a full-fledged web application that is primarily implementing ReactJS, but also contains sections utilizing vanilla JavaScript. Is it possible to host a web app that combines both React and vanilla JavaScript functionalities? (My backend i ...

Struggling with handling numbers and special symbols in the Letter Changes problem on Coderbyte

Hello I have been struggling to find a solution for my current issue. The problem lies within an exercise that requires changing only alphabetical characters, but test cases also include numbers and special characters which are being altered unintentionall ...

To complete Mocha tests, ensure to use the done() method. However, keep in mind that the resolution method is too specific. Choose either to specify a callback *or* return a Promise, but not both simultaneously

Encountering a frustrating issue with a mocha test. When I leave it alone, it freezes and displays: Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. If I include `Pro ...

Struggling to find a solution for changing the color of a select box when an option is chosen

Here's an example of the HTML I'm working with: <select onclick="colorchanger()"> <option name="white" value="0">--Select--</option> <option name="red" value="1">Work</option> <option name="green" value="2" ...

Testing nested mocked functions can be achieved by setting up the necessary mocks

How can I create tests for mocked functions within a mocked function? My goal is to verify that my publish mocked function is called only once. jest.mock('amqplib', () => ({ connect: jest.fn(() => Promise.resolve({ createChannel: jes ...

405 status code returned for CORS request

Hello everyone, I need assistance with my CORS issue. I am trying to make an API request from another domain and encountering an error with the following code: var headers = { host: host, path: url + instance + '?action=reset', ...

Adding new options to a multi-select dropdown in Vue.js when fetching data using an

Greetings! I've been utilizing a modified wrapper to manage a multiple select for vue.js. My goal is to change the value of 'this' inside the vue component. Below is the snippet of my code. <select2-multiple :options="car_options" v-mode ...

Interacting with Django backend via AJAX to trigger Python functions using jQuery/AJAX

Currently, I am developing a small website using Django. Within this project, there are DateTime fields that need to be handled. My intention is to utilize ajax by implementing another button to establish the UTC date while taking into consideration sola ...

Upcoming topics - The Challenge of Staying Hydrated at Basecamp One

I have implemented a themes package for dark mode and light mode in my project. Despite doing the installation correctly as per the repository instructions, I am encountering an issue. My expected behavior for the project is: The webpage should initially ...

Fade in text effect using jQuery on a Mac computer

Trying to create a smooth text fading effect across different browsers using jQuery. In the example below, you may notice that during the last part of the animation when the text fades in, the font weight suddenly increases causing a jerky/clunky appearan ...

Modify path and refresh display upon ajax call to node server

Recently, I made the decision to utilize a Node server as a proxy for making API calls to third-party public APIs from my front end. After successfully sending a request to my Node endpoint and then to the third-party API, I received the expected response. ...

"Organizing a menu in JSON format based on alphabetical

After following this guidance, I successfully created a JSON menu. However, the items are currently sorted by ID and I am in need of sorting them alphabetically. I am unsure about whether using array.sort(); would be applicable in this scenario. Check out ...

Utilizing jQuery time intervals within a jQuery click event: A step-by-step guide

For my dropdown menu project, I am facing an issue where the menu bar is not reappearing after collapsing the dropdown. It seems that the jQuery function responsible for toggling classes within a time interval is not executing properly. Specifically, the " ...

Invalid prop type: A form field received a `checked` prop without a corresponding `onChange` handler

In my project, I have a Parent Component called CandidateList and a Child Component called Candidate. The CandidateList component has a Select All checkbox that triggers a function to set the state when candidates are being selected, and then passes that s ...

Object Literal vs Object-Oriented Javascript: Comparing the Two

When it comes to using Object-Oriented Programming (OOP) in JavaScript, I often find myself not utilizing it much. For instance, instead of defining a constructor function and setting up prototypes like this: function Person(name){ return this.name = name ...

Is it accurate that JavascriptResult displays javascript on the page in a string format?

I am new to .NET MVC and have been experimenting with different return types in MVC. However, I am having trouble getting the JavaScriptResult to work. In my controller, I have the following code: public ActionResult DoSomething() { string s = ...