Implementing a range in HTML time input

Viewed 5953

I have been asked to help fix a bug in a web application that is mostly python (running Flask) which is what I know and why I offered to help. However my HTML knowledge is very bad and I need help. I've fixed the bug in the python code, but I want to make sure the user can't find more ways to break the application. It has to do with the form in HTML where users input the time for a deal. The input is in text format with the placeholder 'hh:mm:ss' but that doesn't stop them from entering all kinds of things other than a time in that format. If I had done this from the beginning I would have made this field a 'time' format but too many things depend on it being a text field now that I would rather just set some validation on this text input field.

The piece of code is:

<input type="text" name="time_left" id="time_left" placeholder="hh:mm:ss">

The only restriction is that the time can't be less than 00:00:00 and it can't be more than 01:30:00. I would love to just put a min/max attribute in here somewhere but I doubt it's that simple. Especially with it being text.

Can anyone advise me what I can do (the simpler the better, as I say, I'm not very good with HTML)

1 Answers

For HTML5 only solutions, there are two ways. One is to make it a type="time" input. It's value can still be read with input.value as a string, if that's of any concern to you.

<input type="time" min="00:00:00" max="01:30:00">

Browsers will allow steps of 1 minute. If you need second precision, add a step="1".

The other solution is to add the pattern attribute:

<input type="text" pattern="0(1:30:00|1:[012][0-9]:[0-5][0-9]|0:[0-5][0-9]:[0-5][0-9])">

Both solutions are viable and each has its advantages and disadvantages.

The latter will have better browser support, but for support closer to 100% you will either way need a JS library that takes over from the browser. I wrote Hyperform, that would do that (and more), but if it's just this one field you might be better off writing your own event handler and attaching it to the change event of that input field.

Edit: The regexp in the pattern attribute will distinguish several cases separated by |. The first and simplest is the max time 01:30:00. The next are the times from 01:00 to 01:29:59, and finally the times from 00:00 to 00:59:59.

Related