使用js来实现简单的form表单验证:
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm(){
var x = document.forms["myForm"]["fname"].value;
var y = document.forms["myForm"]["fsex"].value;
if (x == null || x == ""){
alert("姓必须填写");
return false;
}
if (y == null || y == ""){
alert("性别必须填写");
return false;
}
var z = document.forms["myForm"]["email"].value;
var atpos = z.indexOf("@");
var dotpos = z.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=z.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="xxx.do" οnsubmit="return validateForm()" method="post">
姓名: <input type="text" name="fname">
性别: <input type="text" name="fsex">
Email: <input type="text" name="email">
<input type="submit" value="提交">
</form>
</body>
</html>