Validating text field input

My project uses a text field for a user to submit a math answer. (I tried input=“number” but this was not working for me). I want to limit the input to 0-9, delete, backspace, enter and the left and right arrow keys. It should also only allow a max of 2 digits.

The closest I’ve been was

<input type="text" id="answer" name="answer" onkeypress='return event.charCode >= 48 && event.charCode <= 57'>
But it's not a good solution. It only allows number input, but not the other buttons. Also I didn't like that it was inline, I thought maybe it should be with the rest of my JS. How could I make this validation?

You can only validate text, so it doesn’t make sense to try to handle delete, backspace, or other control keys. Since your validation is so simple, you can actually do this in HTML:

<input type="text" id="answer" name="answer" required pattern="[\d]+" maxlength="2">

The required attribute makes the field required, and the pattern tests for valid input. No JavaScript required. However, there’s a better way, both in terms of your code and the user experience:

<input type="number" min="0" max="99" required >

This way it’s clearer to other programmers, as well as users and even assistive technology that you’re looking for a number between 0 and 99 (inclusive).

There are some other things you can add to make this work better for you. Here’s a quick example I whipped up:

1 Like

This did the trick for me, thanks!