這裡是一個基本的聯絡表單範例,包含了您所要求的字段和一個簡單的驗證碼。
請注意,這只是前端部分的代碼,您需要在後端處理表單提交並驗證驗證碼。
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>聯絡表單</title>
<style>
.error {
color: red;
}
</style>
<script>
function validateForm() {
const name = document.forms["contactForm"]["name"].value;
const phone = document.forms["contactForm"]["phone"].value;
const email = document.forms["contactForm"]["email"].value;
const city = document.forms["contactForm"]["city"].value;
const message = document.forms["contactForm"]["message"].value;
const captcha = document.forms["contactForm"]["captcha"].value;
const hiddenCaptcha = document.forms["contactForm"]["hiddenCaptcha"].value;
let errors = [];
if (!name) {
errors.push("請輸入姓名");
}
if (!phone) {
errors.push("請輸入電話");
}
if (!email) {
errors.push("請輸入電子郵件");
}
if (!city) {
errors.push("請選擇縣市");
}
if (!message) {
errors.push("請輸入留言內容");
}
if (captcha !== hiddenCaptcha) {
errors.push("驗證碼錯誤");
}
if (errors.length > 0) {
document.getElementById("errors").innerHTML = errors.join("<br>");
return false;
}
return true;
}
function generateCaptcha() {
const a = Math.floor(Math.random() * 10);
const b = Math.floor(Math.random() * 10);
document.getElementById("captchaQuestion").innerHTML = `${a} + ${b} = `;
document.getElementById("hiddenCaptcha").value = a + b;
}
</script>
</head>
<body onload="generateCaptcha()">
<h1>聯絡表單</h1>
<form name="contactForm" action="/your-backend-url" method="POST" onsubmit="return validateForm()">
<p>聯絡人姓名(必填):<input type="text" name="name"></p>
<p>電話(必填):<input type="text" name="phone"></p>
<p>email(必填):<input type="email" name="email"></p>
<p>Line:<input type="text" name="line"></p>
<p>台灣各縣市選項(必填):
<select name="city">
<option value="">選擇縣市</option>
<option value="基隆市">基隆市</option>
<!-- 在此添加其他縣市選項 -->
</select>
</p>
<p
<p>留言內容(必填):
<textarea name="message" rows="4" cols="50"></textarea>
</p>
<p> 驗證碼:<span id="captchaQuestion"></span>
<input type="text" name="captcha"> <input type="hidden" name="hiddenCaptcha" id="hiddenCaptcha">
<button type="button" onclick="generateCaptcha()">重新產生驗證碼</button>
</p> <div id="errors" class="error"></div> <input type="submit" value="提交"> </form> </body> </html> ```
這個範例包含了您要求的表單字段、前端驗證和一個簡單的數字相加驗證碼。在提交表單之前,
它會檢查必填字段是否已填寫,並檢查驗證碼是否正確。 您需要將/your-backend-url替換為您後端處理表單提交的URL。
此外,請記住在實際應用中使用更強大的驗證碼系統,如reCAPTCHA。