How to judge that the input in an input input box is a number?

Problem Description:

        This is a problem I encountered when I was working on a project in the company. The reason is that the product requires only numbers in the input box. If the number of digits is incorrect, the user must be prompted, and the user must also be prompted if an illegal character is entered.

Solution process:

        I originally used isNaN, but I always felt that the effect was not good, and then I went to the Internet to find other methods, so I thought of regularization, but I have not been able to use regularization to solve it.

Solution:

        Finally, it returns to isNaN. First post the description of isNaN in w3c:

 

         In other words, its literal meaning is to ask you: "Is the number in brackets a number?" If the return value is true, it means: "It is not a number", otherwise it means: "It is a number." number"

        It feels like I'm talking nonsense, but for beginners there may be mistakes. This function is really simple and rude, and then bind an oninput event to your input input box.

        Among them, there is a slight difference between the oninput event and the other onchange event. Generally speaking, oninput produces results immediately, while onchange settles accounts after autumn, and the results are produced after your operations are completed. Obviously, the former is more suitable for us. In the current scenario, we are equivalent to using this method to monitor the input of the input box, and the result is displayed immediately, and the logic can be written in your oninput method.

        After the oninput event is bound, you can use isNaN inside it, as long as the input is not a number, it can be detected. For example, if you input a letter or other symbols, the result will be available immediately, which is in line with the expected requirements.

        Here are some input examples:

1. D or other letters error

2. 1 No error reporting

3. 12. No error is reported, it should be automatically resolved to 12.0 or 12. That is to say, 12. is also regarded as a correct number

4. 12.. An error is reported, it does not conform to the format of the number, of course an error is reported

5. 00. does not report an error js will parse 00. into 0. (my guess)

6. 0.. error

       This blog post is just to help some beginners, or those who encounter related problems but can’t find a good solution, please detour

Guess you like

Origin blog.csdn.net/qq_41083105/article/details/119035234