【代码笔记】Web-JavaScript-JavaScript表单验证
一,效果图。
二,代码。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript 表单验证</title>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") {
alert("姓必须填写");
return false;
}
}
</script>
<script>
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("@");
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("Not a valid e-mail address");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo-form.php" onsubmit="return validateForm()" method="post">
姓:
<input type="text" name="fname">
<input type="submit" value="提交">
</form>
<form name="myForm" action="demo-form.php" onsubmit="return validateForm();" method="post">
Email:
<input type="text" name="email">
<input type="submit" value="Submit">
</form>
</body>
</html>
参考资料:《菜鸟教程》
本文来自博客园,作者:花儿迎风笑,转载请注明原文链接:https://www.cnblogs.com/yang-guang-girl/p/10231433.html