html
复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>原生JS输入验证</title>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
body {
background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
}
.container {
width: 100%;
max-width: 500px;
background-color: white;
border-radius: 12px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
overflow: hidden;
}
.header {
background: linear-gradient(to right, #4776E6, #8E54E9);
color: white;
padding: 25px 30px;
text-align: center;
}
.header h1 {
font-size: 28px;
margin-bottom: 8px;
}
.header p {
opacity: 0.9;
font-size: 16px;
}
.form-container {
padding: 30px;
}
.form-group {
margin-bottom: 25px;
position: relative;
}
label {
display: block;
margin-bottom: 8px;
font-weight: 600;
color: #333;
font-size: 15px;
}
input {
width: 100%;
padding: 14px 16px;
border: 2px solid #e1e5ee;
border-radius: 8px;
font-size: 16px;
transition: all 0.3s;
}
input:focus {
outline: none;
border-color: #4776E6;
box-shadow: 0 0 0 3px rgba(71, 118, 230, 0.1);
}
.validation-message {
margin-top: 6px;
font-size: 14px;
display: flex;
align-items: center;
height: 20px;
transition: all 0.3s;
}
.success {
color: #2ecc71;
}
.error {
color: #e74c3c;
}
.info {
color: #3498db;
}
.icon {
margin-right: 6px;
font-size: 16px;
}
.btn {
background: linear-gradient(to right, #4776E6, #8E54E9);
color: white;
border: none;
padding: 15px 20px;
width: 100%;
border-radius: 8px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
margin-top: 10px;
}
.btn:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}
.btn:active {
transform: translateY(0);
}
.form-footer {
text-align: center;
margin-top: 25px;
font-size: 14px;
color: #666;
}
.form-footer a {
color: #4776E6;
text-decoration: none;
font-weight: 600;
}
.password-strength {
height: 5px;
background-color: #eee;
margin-top: 10px;
border-radius: 5px;
overflow: hidden;
}
.strength-meter {
height: 100%;
width: 0;
transition: all 0.3s;
}
.weak {
background-color: #e74c3c;
width: 33%;
}
.medium {
background-color: #f39c12;
width: 66%;
}
.strong {
background-color: #2ecc71;
width: 100%;
}
.input-status {
position: absolute;
right: 15px;
top: 40px;
font-size: 18px;
opacity: 0;
transition: all 0.3s;
}
.show {
opacity: 1;
}
.success-input {
border-color: #2ecc71;
}
.error-input {
border-color: #e74c3c;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>表单验证示例</h1>
<p>使用原生JavaScript实现输入验证</p>
</div>
<div class="form-container">
<form id="validationForm">
<div class="form-group">
<label for="email">电子邮箱</label>
<input type="text" id="email" placeholder="请输入您的邮箱">
<span class="input-status">✓</span>
<div class="validation-message"></div>
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" id="password" placeholder="请输入密码">
<span class="input-status">✓</span>
<div class="password-strength">
<div class="strength-meter"></div>
</div>
<div class="validation-message"></div>
</div>
<div class="form-group">
<label for="phone">手机号码</label>
<input type="text" id="phone" placeholder="请输入手机号码">
<span class="input-status">✓</span>
<div class="validation-message"></div>
</div>
<div class="form-group">
<label for="username">用户名</label>
<input type="text" id="username" placeholder="请输入用户名">
<span class="input-status">✓</span>
<div class="validation-message"></div>
</div>
<button type="submit" class="btn">提交表单</button>
</form>
<div class="form-footer">
已有账户?<a href="#">立即登录</a>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const form = document.getElementById('validationForm');
const emailInput = document.getElementById('email');
const passwordInput = document.getElementById('password');
const phoneInput = document.getElementById('phone');
const usernameInput = document.getElementById('username');
// 为每个输入框添加输入事件监听
emailInput.addEventListener('input', validateEmail);
passwordInput.addEventListener('input', validatePassword);
phoneInput.addEventListener('input', validatePhone);
usernameInput.addEventListener('input', validateUsername);
// 表单提交事件
form.addEventListener('submit', function(e) {
e.preventDefault();
// 验证所有字段
const isEmailValid = validateEmail();
const isPasswordValid = validatePassword();
const isPhoneValid = validatePhone();
const isUsernameValid = validateUsername();
if (isEmailValid && isPasswordValid && isPhoneValid && isUsernameValid) {
alert('表单验证成功!数据可以提交了。');
// 在实际应用中,这里可以提交表单数据
} else {
alert('请修正表单中的错误后再提交。');
}
});
// 邮箱验证函数
function validateEmail() {
const email = emailInput.value.trim();
const messageElement = emailInput.parentNode.querySelector('.validation-message');
const statusIcon = emailInput.parentNode.querySelector('.input-status');
if (email === '') {
showMessage(messageElement, '请输入邮箱地址', 'error');
updateInputStatus(emailInput, statusIcon, false);
return false;
}
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
showMessage(messageElement, '邮箱格式不正确', 'error');
updateInputStatus(emailInput, statusIcon, false);
return false;
}
showMessage(messageElement, '邮箱格式正确', 'success');
updateInputStatus(emailInput, statusIcon, true);
return true;
}
// 密码验证函数
function validatePassword() {
const password = passwordInput.value;
const messageElement = passwordInput.parentNode.querySelector('.validation-message');
const statusIcon = passwordInput.parentNode.querySelector('.input-status');
const strengthMeter = passwordInput.parentNode.querySelector('.strength-meter');
if (password === '') {
showMessage(messageElement, '请输入密码', 'error');
updateInputStatus(passwordInput, statusIcon, false);
strengthMeter.className = 'strength-meter';
return false;
}
if (password.length < 6) {
showMessage(messageElement, '密码至少需要6个字符', 'error');
updateInputStatus(passwordInput, statusIcon, false);
strengthMeter.className = 'strength-meter weak';
return false;
}
// 密码强度检测
let strength = 0;
if (password.length >= 8) strength++;
if (/[A-Z]/.test(password)) strength++;
if (/[0-9]/.test(password)) strength++;
if (/[^A-Za-z0-9]/.test(password)) strength++;
if (strength < 2) {
showMessage(messageElement, '密码强度:弱', 'error');
strengthMeter.className = 'strength-meter weak';
} else if (strength < 4) {
showMessage(messageElement, '密码强度:中', 'info');
strengthMeter.className = 'strength-meter medium';
} else {
showMessage(messageElement, '密码强度:强', 'success');
strengthMeter.className = 'strength-meter strong';
}
updateInputStatus(passwordInput, statusIcon, true);
return true;
}
// 手机号验证函数
function validatePhone() {
const phone = phoneInput.value.trim();
const messageElement = phoneInput.parentNode.querySelector('.validation-message');
const statusIcon = phoneInput.parentNode.querySelector('.input-status');
if (phone === '') {
showMessage(messageElement, '请输入手机号码', 'error');
updateInputStatus(phoneInput, statusIcon, false);
return false;
}
const phoneRegex = /^1[3-9]\d{9}$/;
if (!phoneRegex.test(phone)) {
showMessage(messageElement, '手机号码格式不正确', 'error');
updateInputStatus(phoneInput, statusIcon, false);
return false;
}
showMessage(messageElement, '手机号码格式正确', 'success');
updateInputStatus(phoneInput, statusIcon, true);
return true;
}
// 用户名验证函数
function validateUsername() {
const username = usernameInput.value.trim();
const messageElement = usernameInput.parentNode.querySelector('.validation-message');
const statusIcon = usernameInput.parentNode.querySelector('.input-status');
if (username === '') {
showMessage(messageElement, '请输入用户名', 'error');
updateInputStatus(usernameInput, statusIcon, false);
return false;
}
if (username.length < 3) {
showMessage(messageElement, '用户名至少需要3个字符', 'error');
updateInputStatus(usernameInput, statusIcon, false);
return false;
}
if (username.length > 15) {
showMessage(messageElement, '用户名不能超过15个字符', 'error');
updateInputStatus(usernameInput, statusIcon, false);
return false;
}
const usernameRegex = /^[a-zA-Z0-9_]+$/;
if (!usernameRegex.test(username)) {
showMessage(messageElement, '用户名只能包含字母、数字和下划线', 'error');
updateInputStatus(usernameInput, statusIcon, false);
return false;
}
showMessage(messageElement, '用户名格式正确', 'success');
updateInputStatus(usernameInput, statusIcon, true);
return true;
}
// 显示验证消息的辅助函数
function showMessage(element, message, type) {
element.textContent = message;
element.className = 'validation-message ' + type;
// 添加图标
let icon = '';
if (type === 'success') icon = '✓';
else if (type === 'error') icon = '✗';
else if (type === 'info') icon = 'ℹ';
element.innerHTML = `<span class="icon">${icon}</span> ${message}`;
}
// 更新输入框状态的辅助函数
function updateInputStatus(input, statusIcon, isValid) {
if (isValid) {
input.classList.remove('error-input');
input.classList.add('success-input');
statusIcon.classList.add('show');
statusIcon.style.color = '#2ecc71';
} else {
input.classList.remove('success-input');
input.classList.add('error-input');
statusIcon.classList.add('show');
statusIcon.style.color = '#e74c3c';
}
// 如果没有内容,隐藏状态图标
if (input.value.trim() === '') {
statusIcon.classList.remove('show');
input.classList.remove('success-input', 'error-input');
}
}
});
</script>
</body>
</html>