如何用原生JavaScript實(shí)現(xiàn)輸入驗(yàn)證的界面
更新時(shí)間:2025年11月10日 11:02:17 作者:G018_star?sky?
在開發(fā)Web應(yīng)用時(shí),表單驗(yàn)證是一個必不可少的功能,能夠幫助我們確保用戶輸入的數(shù)據(jù)是有效的,這篇文章主要介紹了如何用原生JavaScript實(shí)現(xiàn)輸入驗(yàn)證界面的相關(guān)資料,需要的朋友可以參考下
完整代碼如下:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>原生JS輸入驗(yàn)證</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>表單驗(yàn)證示例</h1>
<p>使用原生JavaScript實(shí)現(xiàn)輸入驗(yàn)證</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">手機(jī)號碼</label>
<input type="text" id="phone" placeholder="請輸入手機(jī)號碼">
<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="#" rel="external nofollow" >立即登錄</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');
// 為每個輸入框添加輸入事件監(jiān)聽
emailInput.addEventListener('input', validateEmail);
passwordInput.addEventListener('input', validatePassword);
phoneInput.addEventListener('input', validatePhone);
usernameInput.addEventListener('input', validateUsername);
// 表單提交事件
form.addEventListener('submit', function(e) {
e.preventDefault();
// 驗(yàn)證所有字段
const isEmailValid = validateEmail();
const isPasswordValid = validatePassword();
const isPhoneValid = validatePhone();
const isUsernameValid = validateUsername();
if (isEmailValid && isPasswordValid && isPhoneValid && isUsernameValid) {
alert('表單驗(yàn)證成功!數(shù)據(jù)可以提交了。');
// 在實(shí)際應(yīng)用中,這里可以提交表單數(shù)據(jù)
} else {
alert('請修正表單中的錯誤后再提交。');
}
});
// 郵箱驗(yàn)證函數(shù)
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;
}
// 密碼驗(yàn)證函數(shù)
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;
}
// 密碼強(qiáng)度檢測
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, '密碼強(qiáng)度:弱', 'error');
strengthMeter.className = 'strength-meter weak';
} else if (strength < 4) {
showMessage(messageElement, '密碼強(qiáng)度:中', 'info');
strengthMeter.className = 'strength-meter medium';
} else {
showMessage(messageElement, '密碼強(qiáng)度:強(qiáng)', 'success');
strengthMeter.className = 'strength-meter strong';
}
updateInputStatus(passwordInput, statusIcon, true);
return true;
}
// 手機(jī)號驗(yàn)證函數(shù)
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, '請輸入手機(jī)號碼', 'error');
updateInputStatus(phoneInput, statusIcon, false);
return false;
}
const phoneRegex = /^1[3-9]\d{9}$/;
if (!phoneRegex.test(phone)) {
showMessage(messageElement, '手機(jī)號碼格式不正確', 'error');
updateInputStatus(phoneInput, statusIcon, false);
return false;
}
showMessage(messageElement, '手機(jī)號碼格式正確', 'success');
updateInputStatus(phoneInput, statusIcon, true);
return true;
}
// 用戶名驗(yàn)證函數(shù)
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, '用戶名只能包含字母、數(shù)字和下劃線', 'error');
updateInputStatus(usernameInput, statusIcon, false);
return false;
}
showMessage(messageElement, '用戶名格式正確', 'success');
updateInputStatus(usernameInput, statusIcon, true);
return true;
}
// 顯示驗(yàn)證消息的輔助函數(shù)
function showMessage(element, message, type) {
element.textContent = message;
element.className = 'validation-message ' + type;
// 添加圖標(biāo)
let icon = '';
if (type === 'success') icon = '?';
else if (type === 'error') icon = '?';
else if (type === 'info') icon = '?';
element.innerHTML = `<span class="icon">${icon}</span> ${message}`;
}
// 更新輸入框狀態(tài)的輔助函數(shù)
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';
}
// 如果沒有內(nèi)容,隱藏狀態(tài)圖標(biāo)
if (input.value.trim() === '') {
statusIcon.classList.remove('show');
input.classList.remove('success-input', 'error-input');
}
}
});
</script>
</body>
</html>
總結(jié)
到此這篇關(guān)于如何用原生JavaScript實(shí)現(xiàn)輸入驗(yàn)證界面的文章就介紹到這了,更多相關(guān)原生JS輸入驗(yàn)證的界面內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
相關(guān)文章
Javascript打印網(wǎng)頁部分內(nèi)容的腳本
有時(shí)候我們只需要打印部分內(nèi)容,因?yàn)楝F(xiàn)在的頁面中廣告和一些相關(guān)內(nèi)容很多,所有用下面的方法,就可以了2008-11-11

