我的代码:
<form id='test' onSubmit="return ValidateForm()">
Name * <input id="name" type="text"><span id="wrongname" class="error">This is a required field</span>
Email* <input id="email" type="text"><span id="wrongemail" class="error">This is a required field</span>
<div>
<input type="submit" value="Submit" >
</div>
</form>
function ValidateForm() {
document.getElementById('test').onsubmit=function(){
if(document.getElementById('name').value=""){
document.getElementById('wrongname').style.display="block";
return false;
}
else{
return true;
}
if (email.value.search( /^[a-zA-Z]+([_\.-]?[a-zA-Z0-9]+)*@[a-zA-Z0-9]+([\.-]?[a-zA-Z0-9]+)*(\.[a-zA-Z]{2,4})+$/ ) == -1){
alert(“Wrong email”);
return false;
}
}
}
.error{
display:none;
color:red;
}
答案 0 :(得分:2)
的变化:
onsubmit
处理程序,因为您在JavaScript onsubmit
移出ValidateForm函数并将此函数指定为提交处理程序alert()
=
比较运算符更改为==
。仅使用一个=
进行分配return true
,因为这会停止执行电子邮件验证email
更改为document.getElementById('email')
更新的代码:
function ValidateForm() {
if (document.getElementById('name').value == "") {
document.getElementById('wrongname').style.display = "block";
return false;
}
if (document.getElementById('email').value.search(/^[a-zA-Z]+([_\.-]?[a-zA-Z0-9]+)*@[a-zA-Z0-9]+([\.-]?[a-zA-Z0-9]+)*(\.[a-zA-Z]{2,4})+$/) == -1) {
alert("Wrong email");
return false;
}
}
document.getElementById('test').onsubmit = ValidateForm;
答案 1 :(得分:2)
这里出现了一些问题:
document.getElementById('test').onsubmit = function () {}
重复onsubmit
属性no wrap - in body
alert(“Wrong email”);
与alert("Wrong email");
不同,会导致解析错误。==
或更好===
,这也会检查它的类型。<强> [更新] 强>
并删除电子邮件的返回true ^^