我创建了一个像这样的注册页面
<form name='registration' action="registration.php" method="post" onSubmit="return formValidation();">
FirstName:<input type = "Text" name = "firstname">
<input type = "submit" name = "register" value="register">
</form>
这是我的javascript函数
function formValidation() {
var fn = document.registration.firstname;
if ( fname_validation( fn ) ) {}
}
function fname_validation( fn ) {
var fn_len = fn.value.length;
var fn_char = /^[A-Za-z]+$/;
if ( fn_len == 0 ) {
alert("first name cannot empty");
return false;
}
if ( !fn.value.match( fn_char ) ) {
alert("first name must enter alphabet only");
return false;
} else {
return true;
}
}
注册表格正在运行,但是如果用户输入了一个号码,它将提醒并重新加载将刷新页面的页面。如果我想在用户输入错误而不刷新页面以保持用户输入时,该怎么办?
答案 0 :(得分:1)
在您的javascript中,您应该返回正确的值...
示例:
function formValidation() {
var fn = document.registration.firstname;
return fname_validation( fn );
}
答案 1 :(得分:0)
在表单提交中添加return false
<form name='registration' action="registration.php" method="post" onSubmit="return formValidation();return false;">
FirstName:<input type = "Text" name = "firstname">
<input type = "submit" name = "register" value="register">
</form>
答案 2 :(得分:0)
防止表单提交只需在formValidation()函数中返回false