我正在尝试通过链接 JS 文件来验证输入来验证用户的输入。但是,当我单击带有错误数据的提交按钮时,表单被提交并且没有给出验证错误。
表格:
<form id="user_form" name="contactForm" action="#" method="GET" onsubmit="return validateForm();">
<p id="first_name" class="input_title">First name <span class="asterisk_red">*</span></p>
<!-- The HTML 5 'Required' attribute will not allow the form to be sent empty. -->
<input class="input_box" type="text" name="first_name" placeholder="Joe" />
<input id="submit_button" type="submit" name="submit" value="Submit"/>
</form>
还有我用来验证的 JS:
function validateForm(){
/* Validate the first name field of the form */
var fn = document.forms['contactForm'].first_name.value;
/* If the Name string is empty then return false and show warning. */
if (fn == ""){
alert("First name must be filled out");
document.forms['contactForm'].first_name.reset();
return false;
}else if(fn.length <= 2){
alert("Your first name must more than two characters");
document.forms['contactForm'].first_name.reset();
return false;
}
}