HTML表单是网页上用来收集用户输入数据的一种元素。表单通常包含输入框、下拉列表、单选框、复选框等控件,用户可以在这些控件中输入或选择相关信息。表单还可以包含提交按钮,用户填写完表单后,点击提交按钮可以将表单数据发送到服务器进行处理。
表单验证是指在用户提交表单数据之前,对表单数据进行校验,以保证数据的正确性和完整性。常见的表单验证包括必填字段验证、格式验证、长度验证等。
以下是一个简单的HTML表单和表单验证的演示代码:
<!DOCTYPE html>
<html>
<head>
<title>表单演示</title>
</head>
<body>
<form action="submit.php" method="post">
<label for="username">用户名:</label>
<input type="text" id="username" name="username" required>
<br>
<label for="password">密码:</label>
<input type="password" id="password" name="password" required>
<br>
<label for="email">邮箱:</label>
<input type="email" id="email" name="email" required>
<br>
<input type="submit" value="提交">
</form>
</body>
</html>
上面的代码中,form
元素定义了一个表单,action
属性指定了表单数据提交到的处理页面,method
属性指定了提交方式。label
元素和input
元素配对使用,id
属性和for
属性关联起来,表示input
元素对应的标签是哪个。required
属性表示该项为必填项。
在提交表单数据之前,还可以添加JavaScript代码进行表单验证,例如:
<!DOCTYPE html>
<html>
<head>
<title>表单演示</title>
<script>
function validateForm() {
var username = document.forms["myForm"]["username"].value;
var password = document.forms["myForm"]["password"].value;
var email = document.forms["myForm"]["email"].value;
if (username == "") {
alert("请输入用户名");
return false;
}
if (password == "") {
alert("请输入密码");
return false;
}
if (email == "") {
alert("请输入邮箱");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="myForm" action="submit.php" method="post" onsubmit="return validateForm()">
<label for="username">用户名:</label>
<input type="text" id="username" name="username">
<br>
<label for="password">密码:</label>
<input type="password" id="password" name="password">
<br>
<label for="email">邮箱:</label>
<input type="email" id="email" name="email">
<br>
<input type="submit" value="提交">
</form>
</body>
</html>
上面的代码中,validateForm()
函数用来验证表单数据,如果数据不合法,则弹出提示框并返回false
,阻止表单提交。onsubmit
属性指定了提交表单时要执行的代码。