表单验证实战:HTML、CSS和JavaScript完整教程
创作时间:
2025-01-22 05:38:49
作者:
@小白创作中心
表单验证实战:HTML、CSS和JavaScript完整教程
在开发Web应用时,表单验证是一个必不可少的功能,能够帮助我们确保用户输入的数据是有效的。在这篇文章中,我们将介绍一个简单但功能齐全的表单验证项目,适合初学者学习和掌握。
项目需求
我们需要实现一个注册表单,其中包括以下几个字段:
- 用户名
- 邮箱
- 密码
- 确认密码
表单需要进行以下验证:
- 所有字段都是必填项。
- 用户名长度应在3到15个字符之间。
- 密码长度应在6到25个字符之间。
- 邮箱格式应有效。
- 密码和确认密码必须匹配。
案例展示
以下是我们将实现的表单页面截图:
如何实现
我们将使用HTML、CSS和JavaScript来实现这个表单验证功能。首先,让我们看看HTML代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<form id="form" class="form">
<h2>Register With Us</h2>
<div class="form-control">
<label for="username">Username</label>
<input type="text" id="username" placeholder="Enter username">
<small>Error message</small>
</div>
<div class="form-control">
<label for="email">Email</label>
<input type="text" id="email" placeholder="Enter email">
<small>Error message</small>
</div>
<div class="form-control">
<label for="password">Password</label>
<input type="password" id="password" placeholder="Enter password">
<small>Error message</small>
</div>
<div class="form-control">
<label for="password2">Confirm Password</label>
<input type="password" id="password2" placeholder="Enter password again">
<small>Error message</small>
</div>
<button type="submit">Submit</button>
</form>
</div>
<script src="script.js"></script>
</body>
</html>
HTML代码解析
- 表单结构:我们定义了一个包含用户名、邮箱、密码和确认密码的表单。
- 输入字段:每个输入字段都包含一个标签和一个小的错误消息提示。
然后是CSS样式,使我们的表单更美观:
@import url('https://fonts.googleapis.com/css?family=Open+Sans&display=swap');
:root {
--success-color: #2ecc71;
--error-color: #e74c3c;
}
* {
box-sizing: border-box;
}
body {
background-color: #f9fafb;
font-family: 'Open Sans', sans-serif;
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
margin: 0;
}
.container {
background-color: #fff;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
width: 400px;
}
h2 {
text-align: center;
margin: 0 0 20px;
}
.form {
padding: 30px 40px;
}
.form-control {
margin-bottom: 10px;
padding-bottom: 20px;
position: relative;
}
.form-control label {
color: #777;
display: block;
margin-bottom: 5px;
}
.form-control input {
border: 2px solid #f0f0f0;
border-radius: 4px;
display: block;
width: 100%;
padding: 10px;
font-size: 14px;
}
.form-control input:focus {
outline: 0;
border-color: #777;
}
.form-control.success input {
border-color: var(--success-color);
}
.form-control.error input {
border-color: var(--error-color);
}
.form-control small {
color: var(--error-color);
position: absolute;
bottom: 0;
left: 0;
visibility: hidden;
}
.form-control.error small {
visibility: visible;
}
.form button {
cursor: pointer;
background-color: #3498db;
border: 2px solid #3498db;
border-radius: 4px;
color: #fff;
display: block;
font-size: 16px;
padding: 10px;
margin-top: 20px;
width: 100%;
}
CSS代码解析
- 全局样式:设置基本的样式,如字体、背景颜色和盒模型。
- 表单样式:定义表单的容器、标题、表单控件和按钮的样式。
- 表单验证样式:使用CSS类显示输入框的成功和错误状态。
最后是JavaScript代码,负责表单验证的逻辑:
const form = document.getElementById('form');
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');
const password2 = document.getElementById('password2');
// 显示错误信息
function showError(input, message) {
const formControl = input.parentElement;
formControl.className = 'form-control error';
const small = formControl.querySelector('small');
small.innerText = message;
}
// 显示成功信息
function showSuccess(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
// 验证邮箱格式
function checkEmail(input) {
const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (re.test(input.value.trim())) {
showSuccess(input);
} else {
showError(input, 'Email is not valid');
}
}
// 检查必填字段
function checkRequired(inputArr) {
inputArr.forEach(function(input) {
if (input.value.trim() === '') {
showError(input, `${getFieldName(input)} is required`);
} else {
showSuccess(input);
}
});
}
// 检查输入长度
function checkLength(input, min, max) {
if (input.value.length < min) {
showError(
input,
`${getFieldName(input)} must be at least ${min} characters`
);
} else if (input.value.length > max) {
showError(
input,
`${getFieldName(input)} must be less than ${max} characters`
);
} else {
showSuccess(input);
}
}
// 检查密码匹配
function checkPasswordsMatch(input1, input2) {
if (input1.value !== input2.value) {
showError(input2, 'Passwords do not match');
}
}
// 获取字段名称
function getFieldName(input) {
return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}
// 事件监听
form.addEventListener('submit', function(e) {
e.preventDefault();
checkRequired([username, email, password, password2]);
checkLength(username, 3, 15);
checkLength(password, 6, 25);
checkEmail(email);
checkPasswordsMatch(password, password2);
});
JavaScript代码解析
- 获取表单元素:通过
getElementById获取表单和各个输入字段的引用。 - 显示错误信息:
showError函数用于显示错误信息,改变表单控件的样式并显示具体的错误信息。 - 显示成功信息:
showSuccess函数用于显示成功信息,改变表单控件的样式为成功状态。 - 验证邮箱格式:
checkEmail函数使用正则表达式验证邮箱格式是否有效。 - 检查必填字段:
checkRequired函数遍历所有输入字段,检查是否为空,并调用showError或showSuccess函数。 - 检查输入长度:
checkLength函数检查输入的字符长度是否在指定范围内。 - 检查密码匹配:
checkPasswordsMatch函数检查两个密码字段是否一致。 - 获取字段名称:
getFieldName函数将输入字段的ID转换为首字母大写的字段名称。 - 事件监听:为表单添加提交事件监听器
知识点总结
- 表单验证:了解如何使用JavaScript进行表单验证,确保用户输入的数据是有效的。
- 正则表达式:学习如何使用正则表达式验证邮箱格式。
- 事件监听:理解如何使用事件监听器处理表单提交事件。
- 动态样式:通过JavaScript动态添加和移除CSS类,实现表单的错误和成功提示。
结束
希望这篇文章对你有所帮助!如果你在实现过程中遇到任何问题,欢迎在评论区留言,我会尽快回复你。或者你有更好的解决方案,也欢迎分享出来,让我们一起进步!
热门推荐
光谱椭偏仪:原理、应用及产品推荐
幸福树的养殖方法和注意事项
2025年重庆各区中考录取分数线!
羽毛球高手不愿透露的三个细节:这样练突然开窍!
口腔溃疡了怎么办?一文详解成因与应对方法
美味健康的洋葱土豆炖排骨(营养丰富,让你一餐搞定)
逆转高血压,他们做对了这件事!早开始做的人早受益了
大学英语四级作文写作练习与范文
第六代战机,特朗普宣布大消息
慢性肾脏病患者饮食指南,这些食物吃起来得注意
深圳限行政策的应对策略与出行规划
历史文物也能拟人化?《物华弥新》开启国风新篇章
小学数学考试“难出天际”?我们究竟需要怎样一张试卷?
机核的第一部电影!《流浪地球2》纪录片是如何炼成的
Excel上下行文字对齐的10种方法
科普 | 琵嘴鸭:三江之源的“水上挖掘机”
琵嘴鸭:湿地中的“勺嘴”精灵
愚人逆位对方心里有我吗
精神方面的司法鉴定怎么做
女生一生气就胸疼怎么回事
《苹果香》走红网络,一曲情深何以触动“心灵”?
2025高考复读最新政策:哪些大学不招复读生?
软件需求整理:如何高效管理和分析用户需求?
解放战争,国军战力天花板是哪个兵团?汤恩伯兵团力压9兵团居首
香肠的配方你了解多少 常见香肠的配料和做法
最旺宅的十种爬藤植物
保卫细胞有叶绿体吗 有什么作用
股票投资中如何克服心理障碍
科普 | 我的焦虑到底是一种情绪,还是一种疾病,我应不应该去医院?
如何找到合适自己的训练重量及次数?