<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<!-- 设置文档字符编码为UTF-8 -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 设置视口,使页面适应不同设备的屏幕大小 -->
<title>表单验证示例</title>
<!-- 设置页面标题 -->
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
/* 设置页面字体和外边距 */
.form-group {
margin-bottom: 15px;
}
/* 设置表单组的底部外边距 */
.form-group label {
display: block;
margin-bottom: 5px;
}
/* 设置标签为块级元素并添加底部外边距 */
.form-group input {
width: 100%;
padding: 8px;
box-sizing: border-box;
}
/* 设置输入框宽度为100%,内边距和盒模型 */
.form-group .error {
color: red;
font-size: 14px;
margin-top: 5px;
}
/* 设置错误消息的颜色、字体大小和顶部外边距 */
.form-group .success {
color: green;
font-size: 14px;
margin-top: 5px;
}
/* 设置成功消息的颜色、字体大小和顶部外边距 */
button {
padding: 10px 15px;
background-color: #007BFF;
color: white;
border: none;
cursor: pointer;
}
/* 设置按钮的内边距、背景色、文字颜色、边框和鼠标指针 */
button:hover {
background-color: #0056b3;
}
/* 设置按钮悬停时的背景色 */
</style>
</head>
<body>
<h2>表单验证示例</h2>
<!-- 页面标题 -->
<form id="myForm">
<div class="form-group">
<label for="name">姓名:</label>
<input type="text" id="name" name="name" required>
<div class="error" id="nameError"></div>
</div>
<!-- 姓名输入框和错误消息显示区域 -->
<div class="form-group">
<label for="email">邮箱:</label>
<input type="email" id="email" name="email" required>
<div class="error" id="emailError"></div>
</div>
<!-- 邮箱输入框和错误消息显示区域 -->
<div class="form-group">
<label for="password">密码:</label>
<input type="password" id="password" name="password" required>
<div class="error" id="passwordError"></div>
</div>
<!-- 密码输入框和错误消息显示区域 -->
<button type="submit">提交</button>
<!-- 提交按钮 -->
</form>
<script>
document.getElementById('myForm').addEventListener('submit', function(event) {
let isValid = true;
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
// 清除之前的错误信息
document.getElementById('nameError').innerText = '';
document.getElementById('emailError').innerText = '';
document.getElementById('passwordError').innerText = '';
// 验证姓名
if (name.trim() === '') {
document.getElementById('nameError').innerText = '姓名是必填项';
isValid = false;
}
// 验证邮箱
if (email.trim() === '') {
document.getElementById('emailError').innerText = '邮箱是必填项';
isValid = false;
} else if (!isValidEmail(email)) {
document.getElementById('emailError').innerText = '邮箱格式不正确';
isValid = false;
}
// 验证密码
if (password.trim() === '') {
document.getElementById('passwordError').innerText = '密码是必填项';
isValid = false;
} else if (password.length < 6) {
document.getElementById('passwordError').innerText = '密码必须至少6个字符';
isValid = false;
}
// 如果验证失败,阻止表单提交
if (!isValid) {
event.preventDefault();
}
});
// 验证邮箱格式的函数
function isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
</script>
</body>
</html>
表单www
最新推荐文章于 2024-07-17 15:26:15 发布