Email 驗證: /^[^\s@]+@[^\s@]+\.[^\s@]+$/
密碼至少 6 碼且包含數字: /^(?=.*[0-9]).{6,}$/
input
或blur
事件。檔名:day16_form_validation.html
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Day16 - 表單驗證</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
form {
width: 300px;
display: flex;
flex-direction: column;
gap: 10px;
}
input {
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
}
.error {
color: red;
font-size: 14px;
}
.success {
color: green;
font-size: 14px;
}
button {
padding: 8px;
background: darkblue;
color: white;
border: none;
cursor: pointer;
}
button:disabled {
background: gray;
}
</style>
</head>
<body>
<h1>登入表單</h1>
<form id="loginForm">
<label>Email:</label>
<input type="text" id="email" placeholder="請輸入 Email">
<span id="emailError" class="error"></span>
<label>密碼:</label>
<input type="password" id="password" placeholder="請輸入密碼">
<span id="passwordError" class="error"></span>
<button type="submit" disabled>登入</button>
</form>
<script>
const emailInput = document.getElementById("email");
const passwordInput = document.getElementById("password");
const emailError = document.getElementById("emailError");
const passwordError = document.getElementById("passwordError");
const loginForm = document.getElementById("loginForm");
const submitBtn = loginForm.querySelector("button");
// 驗證函式
function validateEmail(email) {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
}
function validatePassword(password) {
const regex = /^(?=.*[0-9]).{6,}$/; // 至少6碼,包含數字
return regex.test(password);
}
// 即時驗證
emailInput.addEventListener("input", () => {
if (!validateEmail(emailInput.value)) {
emailError.textContent = "請輸入正確的 Email 格式";
} else {
emailError.textContent = "";
}
checkForm();
});
passwordInput.addEventListener("input", () => {
if (!validatePassword(passwordInput.value)) {
passwordError.textContent = "密碼需至少 6 碼,且包含數字";
} else {
passwordError.textContent = "";
}
checkForm();
});
// 確認表單是否可提交
function checkForm() {
if (validateEmail(emailInput.value) && validatePassword(passwordInput.value)) {
submitBtn.disabled = false;
} else {
submitBtn.disabled = true;
}
}
// 表單送出事件
loginForm.addEventListener("submit", (event) => {
event.preventDefault(); // 阻止預設送出
alert("登入成功!");
});
</script>
</body>
</html>