Javascript检查输入是否是特定字符串

时间:2017-08-01 20:44:12

标签: javascript html validation input

我有一个HTML输入字段,我需要javascript来检查输入此框的输入是否是某个字符串。具体来说,它必须是一个特定的邮政编码,共有9个不同的邮政编码,所有邮政编码都是不同的,没有数字顺序。一旦代码检查它是否是特定的邮政编码,它就会返回"是"如果没有,则返回。

我知道如何使用整数执行此操作,如下面的代码所示,但不确定如何使用字符串执行此操作。这是我当前的代码,它可以验证1-10:

之间的整数



<input id="numb">

<button type="button" onclick="myFunction()">Submit</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x, text;

    // Get the value of the input field with id="numb"
    x = document.getElementById("numb").value;

    // If x is Not a Number or less than one or greater than 10
    if (isNaN(x) || x < 1 || x > 10) {
        text = "Input not valid";
    } else {
        text = "Input OK";
    }
    document.getElementById("demo").innerHTML = text;
}
</script>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:4)

我认为你过分思考这一点。您只需使用indexOf函数来测试您的邮政编码阵列。

&#13;
&#13;
var btn= document.getElementById("btn");
var input = document.getElementById("numb");
var output = document.getElementById("demo"); 
var formArea = document.getElementById("formArea"); 

var zips = ["11111","22222","33333","44444","55555", "e1", "e2"];

btn.addEventListener("click", function() {
    var result = null;

    // indexOf() returns -1 when the supplied value isn't present
    if(zips.indexOf(numb.value.toLowerCase()) > -1){
      result =  "yes";
      
      // Show the form by removing the hidden class
      formArea.classList.remove("hidden");
    } else {
      result = "no";
      // Hide the form by adding the hidden class
      formArea.classList.add("hidden");      
    }
    output.textContent = result;

});
&#13;
#formArea{
  border:2px double grey;
  width:50%;
  box-shadow:2px 2px 0 #303030;
  height:100px;
  padding:5px;
}

.hidden { 
  display:none; 
}
&#13;
<input id="numb">

<button type="button" id="btn">Submit</button>

<p id="demo"></p>

<div id="formArea" class="hidden ">
  Your form goes here
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以为邮政编码使用正则表达式吗?请注意,这是一组字符串格式的邮政编码,但欢迎您创建一个可以满足您感兴趣的邮政编码的邮政编码正则表达式。此外,如果设置足够小,您可以可能只是在列表/集中枚举它们并检查集合是否包含输入。

<input id="numb">

<button type="button" onclick="myFunction()">Submit</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x, text;

    var isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/;

    // Get the value of the input field with id="numb"
    x = document.getElementById("numb").value;

    // If x is Not a Number or less than one or greater than 10
    if (!isValidZip.test(x)) {
        text = "Input not valid";
    } else {
        text = "Input OK";
    }
    document.getElementById("demo").innerHTML = text;
}
</script>

答案 2 :(得分:0)

将其转换为数字

x = Number(document.getElementById("numb").value);