简体   繁体   中英

JavaScript, how to validate if string?

I'm working on a form where my user enters a number between 0-100. If my user puts in 101, it will return with an alert saying that the numbers are invalid. But how do I validate so he doesn't put in something like "asdfasdf" or if it's just empty?

This is my Validate Script:

        function validate() {
        var pct = $('#pct').val();
        if (pct !== "" && (pct > 100 || pct < 0))
            return false;
        else
            return true;
    }

Try this:

function validate() {
   var pct = parseInt($('#pct').val());
   return (pct <= 100) && (pct >= 0);
}

parseInt('not a number') -> NaN Comparison result with NaN is always false. So try represent expression as positive and play with it.

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