问题描述
我正在构建注册表,我需要一种防止用户提交少于5个邮政编码的方法.当我完全注释掉其他选项的尝试时,其他功能(确保用户不会提交任何字母)起作用.我在最后使用return false,以便表单不会提交,并且我可以测试错误的输入.很抱歉缺少jsfiddle-出于某种原因,它不会让我提交表单(我是菜鸟,所以可能是原因).这是我的代码段:
I am building a registration form and I need a way of preventing users from submitting less than 5 numbers for the zip code. When I comment out my attempt for the else if entirely, the other function (making sure that users won't submit any letters) works. I am using return false at the end so that the form won't submit and I can test for bad input. Sorry for the lack of jsfiddle - it wouldn't let me submit forms for some reason (I am a noob, so that may be the reason). Here's a snippet of my code:
HTML:
<form name="reg" onSubmit="return formValidation();">
<p>Zip Code: <input type="text" id="zip" maxlength="5" name="zip"></p>
<input type="submit" id="submitbutton" name="submitbutton" value="Submit" />
<div id="msg"></div>
</form>
JS:
function formValidation()
{
var zip = document.reg.zip;
allnumeric(zip);
function allnumeric(zip)
{
var numbers = /^[0-9]+$/;
if(zip.value.match(numbers))
{
document.getElementById("msg").innerHTML=("OK ✓");
msg.style.color="green";
}
else if (zip.numbers < 5) /*DOES NOT COMPUTE*/
{
msg.innerHTML=("Has to be 5 numbers.");
msg.style.color="red";
}
else
{
msg.innerHTML=("Numbers only please.");
msg.style.color="red";
}
};
return false;
};
推荐答案
您要的是zip.value.length
,而不是zip.numbers
.
您还可以使用正则表达式来完成整个工作:
You can also do the whole thing with the regex:
var numbers = /^\d{5}$/;
if(zip.value.match(numbers))
{
document.getElementById("msg").innerHTML=("OK ✓");
msg.style.color="green";
}
else
{
msg.innerHTML=("Numbers only please.");
msg.style.color="red";
}
这篇关于确保用户以JavaScript格式提交的邮政编码不能少于5个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!