使用JavaScript執(zhí)行表單驗(yàn)證的方法
表單驗(yàn)證的基本概念
什么是表單驗(yàn)證?
表單驗(yàn)證是指在用戶提交表單之前,通過檢查用戶輸入的數(shù)據(jù)是否符合預(yù)定義的規(guī)則,來確保數(shù)據(jù)的完整性和準(zhǔn)確性。常見的驗(yàn)證規(guī)則包括必填字段、數(shù)據(jù)類型、長度限制、格式匹配等。
表單驗(yàn)證的作用
- 提高數(shù)據(jù)質(zhì)量:確保用戶輸入的數(shù)據(jù)符合預(yù)期的要求,減少無效數(shù)據(jù)的提交。
- 提升用戶體驗(yàn):及時反饋用戶輸入的錯誤,避免用戶多次提交無效表單。
- 減輕服務(wù)器壓力:在客戶端進(jìn)行初步驗(yàn)證,減少無效請求對服務(wù)器的壓力。
使用 JavaScript 執(zhí)行表單驗(yàn)證的方法
方法一:使用原生 JavaScript
通過原生JavaScript,可以直接操作DOM元素,實(shí)現(xiàn)簡單的表單驗(yàn)證。
示例一:驗(yàn)證必填字段
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>表單驗(yàn)證示例一</title>
</head>
<body>
<form id="myForm">
<label for="username">用戶名:</label>
<input type="text" id="username" name="username">
<span id="usernameError" style="color: red;"></span><br>
<label for="email">郵箱:</label>
<input type="email" id="email" name="email">
<span id="emailError" style="color: red;"></span><br>
<button type="button" onclick="validateForm()">提交</button>
</form>
<script>
function validateForm() {
let isValid = true;
// 驗(yàn)證用戶名
const username = document.getElementById('username').value;
const usernameError = document.getElementById('usernameError');
if (username.trim() === '') {
usernameError.textContent = '用戶名不能為空';
isValid = false;
} else {
usernameError.textContent = '';
}
// 驗(yàn)證郵箱
const email = document.getElementById('email').value;
const emailError = document.getElementById('emailError');
if (email.trim() === '') {
emailError.textContent = '郵箱不能為空';
isValid = false;
} else if (!isValidEmail(email)) {
emailError.textContent = '郵箱格式不正確';
isValid = false;
} else {
emailError.textContent = '';
}
if (isValid) {
alert('表單提交成功');
document.getElementById('myForm').reset();
}
}
function isValidEmail(email) {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
}
</script>
</body>
</html>
方法二:使用 HTML5 內(nèi)置屬性
HTML5 提供了一些內(nèi)置屬性,如 required、pattern、min、max 等,可以直接在表單元素上使用,簡化驗(yàn)證邏輯。
示例二:使用 HTML5 內(nèi)置屬性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>表單驗(yàn)證示例二</title>
</head>
<body>
<form id="myForm">
<label for="username">用戶名:</label>
<input type="text" id="username" name="username" required minlength="3" maxlength="20"><br>
<label for="email">郵箱:</label>
<input type="email" id="email" name="email" required pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$"><br>
<button type="submit">提交</button>
</form>
<script>
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault();
const form = event.target;
if (form.checkValidity()) {
alert('表單提交成功');
form.reset();
} else {
form.reportValidity();
}
});
</script>
</body>
</html>
方法三:使用 jQuery 插件
jQuery 是一個流行的JavaScript庫,提供了豐富的插件生態(tài),可以簡化表單驗(yàn)證的實(shí)現(xiàn)。
示例三:使用 jQuery Validation 插件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>表單驗(yàn)證示例三</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.3/dist/jquery.validate.min.js"></script>
</head>
<body>
<form id="myForm">
<label for="username">用戶名:</label>
<input type="text" id="username" name="username" required minlength="3" maxlength="20"><br>
<label for="email">郵箱:</label>
<input type="email" id="email" name="email" required pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$"><br>
<button type="submit">提交</button>
</form>
<script>
$(document).ready(function() {
$('#myForm').validate({
rules: {
username: {
required: true,
minlength: 3,
maxlength: 20
},
email: {
required: true,
email: true
}
},
messages: {
username: {
required: '用戶名不能為空',
minlength: '用戶名至少需要3個字符',
maxlength: '用戶名最多20個字符'
},
email: {
required: '郵箱不能為空',
email: '郵箱格式不正確'
}
},
submitHandler: function(form) {
alert('表單提交成功');
form.reset();
}
});
});
</script>
</body>
</html>
方法四:使用正則表達(dá)式
正則表達(dá)式是一種強(qiáng)大的文本匹配工具,可以用于復(fù)雜的驗(yàn)證規(guī)則,如電話號碼、郵政編碼等。
示例四:使用正則表達(dá)式驗(yàn)證電話號碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>表單驗(yàn)證示例四</title>
</head>
<body>
<form id="myForm">
<label for="phone">電話號碼:</label>
<input type="text" id="phone" name="phone">
<span id="phoneError" style="color: red;"></span><br>
<button type="button" onclick="validateForm()">提交</button>
</form>
<script>
function validateForm() {
const phone = document.getElementById('phone').value;
const phoneError = document.getElementById('phoneError');
const regex = /^1[3-9]\d{9}$/;
if (!regex.test(phone)) {
phoneError.textContent = '電話號碼格式不正確';
} else {
phoneError.textContent = '';
alert('表單提交成功');
document.getElementById('myForm').reset();
}
}
</script>
</body>
</html>
方法五:使用自定義函數(shù)
對于復(fù)雜的驗(yàn)證邏輯,可以編寫自定義函數(shù)來處理特定的驗(yàn)證需求。
示例五:使用自定義函數(shù)驗(yàn)證密碼強(qiáng)度
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>表單驗(yàn)證示例五</title>
</head>
<body>
<form id="myForm">
<label for="password">密碼:</label>
<input type="password" id="password" name="password">
<span id="passwordError" style="color: red;"></span><br>
<button type="button" onclick="validateForm()">提交</button>
</form>
<script>
function validateForm() {
const password = document.getElementById('password').value;
const passwordError = document.getElementById('passwordError');
if (!isStrongPassword(password)) {
passwordError.textContent = '密碼強(qiáng)度不足';
} else {
passwordError.textContent = '';
alert('表單提交成功');
document.getElementById('myForm').reset();
}
}
function isStrongPassword(password) {
const regex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/;
return regex.test(password);
}
</script>
</body>
</html>
不同角度的功能使用思路
多步驟表單驗(yàn)證
在復(fù)雜的表單中,可以將驗(yàn)證邏輯拆分為多個步驟,逐步引導(dǎo)用戶完成表單填寫。
示例六:多步驟表單驗(yàn)證
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>多步驟表單驗(yàn)證示例</title>
</head>
<body>
<form id="multiStepForm">
<div id="step1">
<label for="username">用戶名:</label>
<input type="text" id="username" name="username" required minlength="3" maxlength="20"><br>
<button type="button" onclick="nextStep(1)">下一步</button>
</div>
<div id="step2" style="display: none;">
<label for="email">郵箱:</label>
<input type="email" id="email" name="email" required pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$"><br>
<button type="button" onclick="prevStep(1)">上一步</button>
<button type="button" onclick="nextStep(2)">下一步</button>
</div>
<div id="step3" style="display: none;">
<label for="phone">電話號碼:</label>
<input type="text" id="phone" name="phone" required pattern="^1[3-9]\d{9}$"><br>
<button type="button" onclick="prevStep(2)">上一步</button>
<button type="button" onclick="submitForm()">提交</button>
</div>
</form>
<script>
function nextStep(step) {
const form = document.getElementById('multiStepForm');
const currentStep = document.getElementById(`step${step}`);
const nextStep = document.getElementById(`step${step + 1}`);
if (validateStep(currentStep)) {
currentStep.style.display = 'none';
nextStep.style.display = 'block';
}
}
function prevStep(step) {
const currentStep = document.getElementById(`step${step + 1}`);
const prevStep = document.getElementById(`step${step}`);
currentStep.style.display = 'none';
prevStep.style.display = 'block';
}
function validateStep(step) {
const inputs = step.querySelectorAll('input');
for (const input of inputs) {
if (!input.validity.valid) {
input.reportValidity();
return false;
}
}
return true;
}
function submitForm() {
const form = document.getElementById('multiStepForm');
if (form.checkValidity()) {
alert('表單提交成功');
form.reset();
} else {
form.reportValidity();
}
}
</script>
</body>
</html>
實(shí)時驗(yàn)證
通過監(jiān)聽輸入事件,實(shí)現(xiàn)實(shí)時驗(yàn)證,及時反饋用戶輸入的錯誤。
示例七:實(shí)現(xiàn)實(shí)時驗(yàn)證
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>實(shí)現(xiàn)實(shí)時驗(yàn)證示例</title>
</head>
<body>
<form id="myForm">
<label for="username">用戶名:</label>
<input type="text" id="username" name="username" required minlength="3" maxlength="20">
<span id="usernameError" style="color: red;"></span><br>
<label for="email">郵箱:</label>
<input type="email" id="email" name="email" required pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$">
<span id="emailError" style="color: red;"></span><br>
<button type="button" onclick="validateForm()">提交</button>
</form>
<script>
function validateInput(input, errorSpan, regex, message) {
const value = input.value.trim();
if (value === '') {
errorSpan.textContent = `${input.name}不能為空`;
} else if (!regex.test(value)) {
errorSpan.textContent = message;
} else {
errorSpan.textContent = '';
}
}
document.getElementById('username').addEventListener('input', function() {
const username = this;
const usernameError = document.getElementById('usernameError');
const regex = /^.{3,20}$/;
validateInput(username, usernameError, regex, '用戶名長度應(yīng)在3到20個字符之間');
});
document.getElementById('email').addEventListener('input', function() {
const email = this;
const emailError = document.getElementById('emailError');
const regex = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/;
validateInput(email, emailError, regex, '郵箱格式不正確');
});
function validateForm() {
const username = document.getElementById('username');
const email = document.getElementById('email');
const usernameError = document.getElementById('usernameError');
const emailError = document.getElementById('emailError');
if (usernameError.textContent || emailError.textContent) {
return;
}
alert('表單提交成功');
document.getElementById('myForm').reset();
}
</script>
</body>
</html>
實(shí)際開發(fā)中的注意事項(xiàng)
在實(shí)際的Web前端開發(fā)中,合理地使用表單驗(yàn)證可以帶來許多好處,但也需要注意以下幾點(diǎn):
在實(shí)際的Web前端開發(fā)中,合理地使用表單驗(yàn)證可以帶來許多好處,但也需要注意以下幾點(diǎn):
- 用戶體驗(yàn):及時反饋用戶輸入的錯誤,避免用戶多次提交無效表單。
- 兼容性:確保驗(yàn)證邏輯在不同的瀏覽器和設(shè)備上都能正常運(yùn)行。
- 安全性:客戶端驗(yàn)證只是初步檢查,服務(wù)器端仍需進(jìn)行二次驗(yàn)證,確保數(shù)據(jù)的安全性。
- 性能:避免過度復(fù)雜的驗(yàn)證邏輯,影響頁面的加載和響應(yīng)速度。
總之,表單驗(yàn)證是Web前端開發(fā)中的一個重要環(huán)節(jié),通過合理地使用JavaScript,可以有效地提升用戶體驗(yàn)和數(shù)據(jù)的可靠性。希望本文提供的信息能幫助你在未來的項(xiàng)目中更好地實(shí)現(xiàn)表單驗(yàn)證功能。
以上就是使用JavaScript執(zhí)行表單驗(yàn)證的方法的詳細(xì)內(nèi)容,更多關(guān)于JavaScript執(zhí)行表單驗(yàn)證的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
JavaScript前端無法獲取響應(yīng)頭原因與解決方案
這篇文章主要為大家詳細(xì)介紹了JavaScript前端無法獲取響應(yīng)頭原因與解決方案,如 Content-Disposition,下面小編就來和大家詳細(xì)介紹一下吧2025-08-08
使用Web Uploader實(shí)現(xiàn)多文件上傳
這篇文章主要介紹了使用Web Uploader實(shí)現(xiàn)多文件上傳的相關(guān)資料,非常不錯具有參考借鑒價值,需要的朋友可以參考下2016-06-06
利用uni-app和uView實(shí)現(xiàn)多圖上傳功能全過程
最近在使用uniapp開發(fā)的微信小程序中使用了圖片上傳功能,下面這篇文章主要給大家介紹了關(guān)于利用uni-app和uView實(shí)現(xiàn)多圖上傳功能的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-03-03
JS實(shí)現(xiàn)的Select三級下拉菜單代碼
這篇文章主要介紹了JS實(shí)現(xiàn)的Select三級下拉菜單,涉及javascript動態(tài)創(chuàng)建下拉列表的技巧,非常具有實(shí)用價值,需要的朋友可以參考下2015-08-08
JS實(shí)現(xiàn)點(diǎn)擊登錄彈出窗口同時背景色漸變動畫效果
這篇文章主要介紹了JS實(shí)現(xiàn)點(diǎn)擊登錄彈出窗口同時背景色漸變動畫效果,涉及JavaScript基于鼠標(biāo)事件及時間函數(shù)定時觸發(fā)形成漸變動畫的相關(guān)技巧,需要的朋友可以參考下2016-03-03
JavaScript實(shí)現(xiàn)從數(shù)組中選出和等于固定值的n個數(shù)
這篇文章主要介紹了JavaScript實(shí)現(xiàn)從數(shù)組中選出和等于固定值的n個數(shù)的方法,需要的朋友可以參考下2014-09-09
JS實(shí)現(xiàn)數(shù)組內(nèi)值累加常見的3個方法
這篇文章主要給大家介紹了關(guān)于JS實(shí)現(xiàn)數(shù)組內(nèi)值累加常見的3個方法,文中通過實(shí)例代碼將3個方法介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用js具有一定參考借鑒價值,需要的朋友可以參考下2023-07-07

