I have a simple code that allows the user to enter minutes and seconds (website is written in react).
<div>
<span>
<input defaultValue="0" maxlength="2"/>
</span>
<span>m</span>
<span>
<input defaultValue="10" maxLength='2' />
</span>
<span>s</span>
</div>
But I would like to improve my functionality and that’s why I’m turning to you.
Currently the user can enter any number <= 99 (and in the seconds column he can enter 99) and any characters, but I would like the user to be able to enter a time of at least 5 seconds and at most 20 minutes.
Tell me how to limit the entered characters to numbers only and limit the maximum and minimum entered time.
4
Answers
You can validate it using onChange handler of input.
You can validate input data in validtionFunc.
Thank you.
You have to use an
<input type="number" />
with the appropriatemin
andmax
.In order to achieve the limitation of
> 5"
and< 20'
, you need a bit of state logic:Not fully tested but you could try an approach like this.
Once you have set the input fields with the appropriate
type
attribute, such astype='number'
and ensure that themin
andmax
attributes are set to your criteria ( max 20mins, min 5sec ) you can then use a delegated listener bound to a suitable parent (the document in this case but could/should be more focused) that monitors theinput
event.The event handler identifies all the
input
elements of relevance ( by name here ) and performs some basic operations on the values of each to create a total time value in seconds. If that time value is beyond your limits warn the user &/or set your own default value.To do that with only Javascript and show an alert on invalid input: