我编写了一个 javascript 函数来验证表单上的字段。此函数应该确保字段不为空,不超过 35 个字符的限制,并且只包含字母字符和连字符 (-)。我有代码来确保该字段不为空并且它不超过 35 个字符,这工作正常,但我添加了代码来验证该字段是否为可用字符,我通过将该字段留空以确保它仍然有效来测试它但是当我点击提交按钮时,该功能似乎根本没有验证,没有给我警报,只是提交了。这是我的代码:
function validateFamily()
{
var family=document.getElementById('family');
var stringf = document.getElementById('family').value;
if (family.value=="")
{
alert("Family name must be filled out");
return false;
}
else if (document.getElementById('family').value.length > 35)
{
alert("Family name cannot be more than 35 characters");
return false;
}
else if (/[^a-zA-Z\-\]/.test( stringf ))
{
alert("Family name can only contain alphanumeric characters and hypehns(-)")
return false;
}
return true;
}
<form name="eoiform" method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi" onsubmit="return validateFamily() && validateGiven() && validateMaleFemale() && validDate() && validateAddress() && validatePost() && validateParent() && validateWork() && validateHome() && validateMob() && validateCheckBoxes();">
<b>Student's Family Name</b>
<br>
<input type="text" id="family" name="family" /><?php echo $strmsgf; ?>
<input type="submit" name="submit" id="submit" value="submit" />
</form>
谁能告诉我如何修复我的代码?