提交时Javascript验证不起作用
我一直在开发我的第一个网站,我在javascript验证脚本方面遇到了问题。我的代码:提交时Javascript验证不起作用,javascript,html,Javascript,Html,我一直在开发我的第一个网站,我在javascript验证脚本方面遇到了问题。我的代码: <html> <head> <title>Territory</title> </head> <body> <script type="text/javascript"> //Main Javascript function giving me issues funct
<html>
<head>
<title>Territory</title>
</head>
<body>
<script type="text/javascript"> //Main Javascript function giving me issues
function validate(form)
{
fail = validateTerrNum(document.checkOut.numberOut.value);
fail += validateFirstName(document.checkOut.fName.value);
fail += validateLastName(document.checkOut.lName.value);
if (fail == "")
return true;
else
{
alert(fail);
return false;
}
}
</script>
<script type="text/javascript>
function validateTerrNumber(field)
{
if (field == "") return "No territory number was entered. \n";
else if (field.length > 3)
return "Territory numbers must be less than four characters. \n";
else if (/[^0-9]/.test(field))
return "Only 0-9 allowed in territory number. \n";
return "";
}
//Note: Does not sanitize string
function validateFirstName(field)
{
if (field == "") return "No first name was entered. \n";
return "";
}
//Again, note that this function does not sanitize string
function validateLastName(field)
{
if (field == "") return "Not last name was entered. \n";
return "";
}
</script>
<table border="0" cellpadding="2" cellspacing="5">
<th colspan="2" align="center">Check Out</th>
<form name="checkOut" method="post" onSubmit="validate(this)">
<tr><td>Territory Number</td><td><input type="text" name="numberOut" tabindex="1" maxlength="3" size="3" /></td>
</tr><tr><td>First Name of Holder</td><td><input type="text" name="fName" tabindex="2" maxlength="15"/></td>
</tr><tr><td>Last Name of Holder</td><td><input type="text" name="lName" tabindex="3" maxlength="15" /></td>
</tr><tr><td><input type ="checkbox" name="specialC" tabindex="4" value="Yes"/> Special Campaign</td>
</tr><tr><td></td><td><input type="submit" value="Check Out" /></td>
</form>
</table>
</body>
</html>
领地
//主要Javascript函数给我带来了一些问题
函数验证(表单)
{
失败=ValidateTernum(document.checkOut.numberRout.value);
fail+=validateFirstName(document.checkOut.fName.value);
fail+=validateLastName(document.checkOut.lName.value);
如果(失败==“”)
返回true;
其他的
{
警报(失败);
返回false;
}
}
在validate()
中有这一行:
还有这个功能:
function validateTerrNumber(field){...
另外,document.checkOut
是未定义的
而不是表单
元素(依赖浏览器???),最好使用document.getElementById('numberrout')。value
(与fName
和lName
相同)。当然,您需要在HTML中添加这些id
s。要在验证失败后停止提交,您需要:
onSubmit="return validate(this)"
而不是您当前的代码:
onSubmit="validate(this)"
validate()
函数已返回true
或false
,但这些值不是从事件处理程序本身返回的。如果您认为onSubmit=“
的引号之间的代码是函数的主体,这是有意义的
而且,Astemu指出,您的validate()
函数试图调用名为validateternum
的函数,而实际上您已将该函数声明为validateternumber
纠正了这些问题后,您可以看到它在这里工作:为什么不尝试将“提交”按钮设置为一个按钮,并从该按钮调用java脚本。如果验证通过,只需调用form.submit();感谢您的反馈;这立刻解决了问题。我不敢相信我完全错过了。我当然更喜欢document.getElementById()
,但是document.checkOut
在我的答案中包含的演示中工作得很好。(如果你想使用getElementById()
你应该给元素ID…)你阻止了我遇到一个我还没有遇到的问题,谢谢。
onSubmit="validate(this)"