ZipCode验证格式nnnnn-nnnn

时间:2017-04-08 17:45:58

标签: javascript html json

ZipCode验证格式nnnnn-nnnn。当用户输入“ - ”时,它被计为一个数字,它将从我所做的最大数字9中取出,并且由于用户输入“ - ”它将只允许8.我怎么能跳过“ - “不要数字并输入正确的输入代码

function formatZipCode(value) {
    value = value.replace(/[^\/\d]/g,'');
    var Z = /(\d{5})(\d)/;
    if (value != undefined && value != '') {
        return value = value.replace(Z, '$1' + '-' + '$2');;
    }
    else {
        return value;
    }
};

2 个答案:

答案 0 :(得分:1)

我会使用以下内容:

var z = /(\d{5})-?(\d{4})/
value = value.replace(z,"$1-$2")

连字符后的问号表示零个或一个连字符。

答案 1 :(得分:1)

如果它是用户输入的HTML表单,则可以使用它来验证邮政编码:

  
      
  • <input type='number'> - 消除字母和符号
  •   
  • minmax属性 - 强制执行范围
  •   
  • <input type='submit'> - 允许内置验证<form>
  •   

添加了验证数字的附加功能

  

首先输入必须是10000到99999

     

     

第二个输入必须是1000到9999

<强>段

&#13;
&#13;
/* Ensures input is 5 and 4 digits by
|| disabling submit button when 
|| requirements are not met.
*/
function digits(num1, num2) {
  var n1 = num1.length;
  var n2 = num2.length;
  if (n1 === 5 && n2 === 4) {
    zip['submit'].disabled = false;
  } else {
    zip['submit'].disabled = true;
  }
}
&#13;
input {
  font: inherit
}

#z4 {
  width: 6ch;
}

#z5 {
  width: 7ch;
}

fieldset {
  width: 13em;
}

legend,
[type=submit] {
  font-variant: small-caps;
}
&#13;
<!--
Ensures input is within 10000 - 99999 and
1000 - 9999 by invalidating onsubmit
-->
<form id='zip' name='zip' action='http://httpbin.org/post' method='post' onchange='digits(z5.value, z4.value)'>
  <fieldset>
    <legend>Zipcode</legend>
    <input id='z5' name='z5' type='number' size='5' value='00000' min='10000' max='99999'>-<input id='z4' name='z4' type='number' size='4' value='0000' min='1000' max='9999'>
    <input type='submit' id='submit' disabled>
  </fieldset>
</form>
&#13;
&#13;
&#13;