-3

我需要验证我的表格的一部分,它是基于马来西亚邮政编码的邮政编码,这是一个 5 位数字邮政编码。如何验证用户输入的值只有 5 个数字,不多也不少?提前致谢!

这是我的部分代码:

HTML:

<label>Postcode: <input type="text" name="postcode" id="postcode" required="required"></label><br />

Javascript:

function chkPostcode () {
    var postcode = document.getElementById("postcode").value;
    var pattern = /^[0-9]+$/; //check only alpha characters or space
    var postcodeOK = true;
    
    if ((postcode.length < 5 && postcode.length > 5)){ //same as owner==""
        gErrorMsg = gErrorMsg + "Please enter postcode.\n"
        postcodeOK = false; //if condition or clause complex more readable if branches on separate lines
    }
    else{
        if (!pattern.test(postcode)){
        gErrorMsg = gErrorMsg + "Postcode must only contain numbers.\n"
        postcodeOK = false; //if condition or clause complex more readable if branches on separate lines
        }
    }
//if (!nameOk){
// document.getElementById("owner").style.borderColor = "red";
//
    return postcodeOK;
}
4

2 回答 2

1

对于您要完成的工作,这是一个更短的代码。

document.getElementById("postcode").addEventListener("input", function(e) {
  if ( /^\d{5}$/.test(e.target.value)){
    console.log("valid");
    return;
  }
  console.log("invalid");
})
<label>Postcode: <input type="text" name="postcode" id="postcode" required="required"></label><br />

于 2021-05-08T07:08:25.643 回答
-5

Your JavaScript is unnecessarily complicated. Here's a sure (and much better) way (except for all the ifs) to do this (the button and the check function are just for demo purposes):

function chkPostcode() {
   var postcode = document.getElementById("postcode").value;
   if(postcode.length !== 5)
   {
    return false;
   }
   else {
    if(!isNaN(parseInt(postcode.charAt(0)))) {
      if(!isNaN(parseInt(postcode.charAt(1)))) {
        if(!isNaN(parseInt(postcode.charAt(2)))) {
          if(!isNaN(parseInt(postcode.charAt(3)))) {
            if(!isNaN(parseInt(postcode.charAt(4)))) {
              return true;
            }
          }
        }
      }
    }
   }
   return false;
}
function check() {
  if(chkPostcode()) alert("Valid!");
  else alert("Not a postcode");
}
<input type="text" id="postcode" />
<button onclick="check()">Check</button>

Just keep in mind, although client side (JavaScript) validation scripts are helpful, it's easy to defeat client-side JavaScript. Make sure you make some validation on the server-side as well, where the client can't tamper with the code as easily.

于 2021-05-08T06:31:42.813 回答