简体   繁体   中英

Validate that input is between 2 numbers in javascript

I am currently using Google maps and attempting to use input validation. I require the user to use a number between 0 and 20 to set as a zoom on my location.

Below is the code I am using. The first if statement works perfectly for any number over 20 but the second does not work when I use numbers like 0 and -1 (for instance.)

Any suggestions for fixing this?

function inputIsValid() {

                       console.log("Inside inputIsValid function");

                       //Check for Above 20
                       if (document.getElementById("txtZoom").value  > 20) {
                           alert("Please insertAmount between 0 and 20");
                           document.getElementById("txtZoom").focus();
                           return false;

                           //Check for Number below 0
                           if (document.getElementById("txtZoom").value < 0) {
                               alert("Please insertAmount between 0 and 20");
                               document.getElementById("txtZoom").focus();
                               return false;
                           }
                       }
                   }

The problem is you nested the second check within the first, so it will never be reached. Try this:

function inputIsValid() {
    var zoomValue = document.getElementById("txtZoom").value;

    if (zoomValue > 20 || zoomValue < 0) {
         alert("Please insertAmount between 0 and 20");
         document.getElementById("txtZoom").focus();
         return false;
    }
}
   function inputIsValid() {
   $value = document.getElementById("txtZoom").value;

   if (($value  < 0) && ($value  > 20)) {
   alert("Please enter a value between 0 and 20");
   return false;
   }

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