-5

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;
    }
Foo Bar
  • 87
  • 2
  • 10
  • 7
    Possible duplicate of [Check whether variable is number or string in javascript](http://stackoverflow.com/questions/1303646/check-whether-variable-is-number-or-string-in-javascript) – g00glen00b Oct 06 '15 at 12:19
  • Possible duplicate of hundreds of similar questions… – Touffy Oct 06 '15 at 12:19
  • Indeed: http://stackoverflow.com/questions/2652319/how-do-you-check-that-a-number-is-nan-in-javascript http://stackoverflow.com/questions/154059/how-do-you-check-for-an-empty-string-in-javascript http://stackoverflow.com/questions/1303646/check-whether-variable-is-number-or-string-in-javascript ... – g00glen00b Oct 06 '15 at 12:21

1 Answers1

0

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.

RedJabber
  • 101
  • 1
  • 5