简体   繁体   中英

How to find that a value is less than 108 and greater than 0 in JavaScript: something wrong in script

I write this code for checking:

var num = $("#knum").val();
        if (isNaN(parseInt(num))) {
            $("#errorknum").html("Please define a number.");
        }
        else {
            if (num < 1 | num > 249) {
                $("#errorkrnum").html("your number must be less then 249 and can be greater than 1");
            }
            else {
                $("#errorknum").html("");
            }

Everything is fine but, for example, when the user type 1242fdlfldsf means it is 1242 but she accept it. How can I dishandle this value by code like for example: 23232dkfj

parseInt() should always be used with the second argument, in order to tell it that you expect a base-10 number:

parseInt(num, 10)

Also, you don't save its results so you are comparing strings.

And the single | is a bitwise operator. You probably want || .

Also, when you do your OR comparison, you need to be using || not |:

if (num < 1 || num > 249)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM