Validate input, if an invalid character is entered, then stop the input until the correct character. How can you do it?
-
For example, this input stops when there are 2 characters. Or how can you get the pressed character before it appears in input and validate the pressed character and if that stop?
The validation function will be in the javascript function.
& lt; input type = "text" maxlength = 2 & gt;
JavaScript Leah Michael, Jul 28, 2020 -
Well, for example, if you can enter only numbers and delete any other characters.
In the first option, unnecessary characters are deleted, and in the second, there is a check when pressed, i.e. they are not even entered.
Anonymous -
A very primitive way:
In this example, we take each charactere.key
and validate it withe.key! == '1'
. If the entered character is not a unit, then it is not entered, otherwise -if (e.key! == '1') return false;
. Instead of checking a condition with one, you can, for example, specify your own validation function:if (keyValidation (e.key)) return false;
Anonymous -
<input type="text" maxlength=2 onInput="chFunc(this);">
And in the chFunc function, checkConner Porter
3 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!