验证javascript中的输入是否在2个数字之间

Validate that input is between 2 numbers in javascript

本文关键字:2个 数字 之间 是否 输入 javascript 验证      更新时间:2023-12-25

我目前正在使用谷歌地图并尝试使用输入验证。我要求用户使用0到20之间的数字来设置我的位置缩放。

下面是我正在使用的代码。第一个if语句适用于任何超过20的数字,但当我使用0和-1这样的数字时(例如),第二个语句不起作用

有什么解决这个问题的建议吗?

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;
                           }
                       }
                   }

问题是您将第二个检查嵌套在第一个检查中,因此永远无法到达。试试这个:

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;
   }