Validate input, if an invalid character is entered, then stop the input until the correct character. How can you do it?

  • 0
    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

  • 3 Answers
  • 0
    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

  • 0
    A very primitive way:





    In this example, we take each character e.key and validate it with e.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

  • 0
    <input type="text" maxlength=2 onInput="chFunc(this);">




    And in the chFunc function, check
    Conner Porter

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!