一,效果圖。 二,代碼。 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JavaScript 表單驗證</title> <script> function validateForm() { var x = document.f ...
一,效果圖。
二,代碼。
<!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>
參考資料:《菜鳥教程》