表單是網站裡最常見的互動方式之一,登入、註冊、搜尋、留言……這些功能幾乎都要用到表單。
今天要學習如何用JavaScript處理表單輸入,以及做一些基本的驗證
在 HTML 裡,常見的表單元素有 <input>
、<textarea>
、<select>
每個表單元素在JS裡都有一個value
屬性,能讀取或修改使用者輸入的內容
範例:
<input type="text" id="username" placeholder="輸入帳號">
<button id="submitBtn">送出</button>
<script>
const usernameInput = document.querySelector('#username');
const btn = document.querySelector('#submitBtn');
btn.addEventListener('click', () => {
console.log(usernameInput.value);
});
</script>
如果你的表單是用<form>
包起來的,通常會用submit事件監聽
<form id="myForm">
<input type="text" id="email" placeholder="輸入 email">
<button type="submit">送出</button>
</form>
<script>
const form = document.querySelector('#myForm');
const emailInput = document.querySelector('#email');
form.addEventListener('submit', (e) => {
e.preventDefault(); // 防止表單送出刷新頁面
console.log(emailInput.value);
});
</script>
js可以檢查使用者的輸入內容是否符合需要的格式,以免使用者亂填入內容
1.if條件判斷
範例:
if (emailInput.value === '') {
alert('Email 不能空白!');
}
2.正規表達式
正規表達式寫法通常像這樣
const pattern = /abc/;
用/
包起來的部分就是正規表達式,而只要字串的部分內容符合用/
判斷為正確
然後我們可以用.test(string)
檢查字串是否符合規則
範例:
/abc/.test("abcdef"); // true
/abc/.test("xyz"); // false
那麼實際上如何檢查特定的格式呢?
我們就需要使用特殊字元來告訴它該如何檢查
符號 | 意義 | 範例 |
---|---|---|
^ |
開頭 | /^a/ 必須以a開頭 |
$ |
結尾 | /z$/ 必須以z結尾 |
. |
任意單一字元 | /a.b/ → a和b中間可以是任意一個字 |
\d |
一個數字 (0–9) | /\d/ → "8" |
\w |
一個字元(a-z,A-Z,0-9,_) |
/\w/ → "A" |
\s |
空白字元 | /\s/ |
+ |
至少一次 | /a+/ → "aaa" |
* |
0次或多次 | /a*/ → "","a","aaa" |
? |
0次或1次 | /a?/ → "" 或 "a" |
{n,m} |
次數範圍 | /a{2,4}/ → "aa","aaa","aaaa" |
[] |
字元集合 | /[abc]/ → "a" 或 "b" 或 "c" |
[^] |
取反 | /[^0-9] / → 非數字 |
範例:
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(emailInput.value)) {
alert('Email 格式不正確!');
}
3.即時驗證
除了送出時檢查,也可以在輸入過程中即時提示
範例:
const usernameInput = document.querySelector('#username');
usernameInput.addEventListener('input', (e) => {
if (e.target.value.length < 3) {
errorMessage.textContent = '使用者名稱太短';
} else {
errorMessage.textContent = '';
}
});
小練習
<form id="loginForm">
<input type="text" id="username" placeholder="帳號">
<input type="password" id="password" placeholder="密碼">
<button type="submit">登入</button>
</form>
<script>
const loginForm = document.querySelector('#loginForm');
const username = document.querySelector('#username');
const password = document.querySelector('#password');
loginForm.addEventListener('submit', (e) => {
e.preventDefault();
if (username.value === '' || password.value === '') {
alert('帳號和密碼不可為空白');
return;
}
if (password.value.length < 6) {
alert('密碼至少要6碼');
return;
}
alert('登入成功!');
});
</script>
整理一下今天的內容:
1.value
屬性可以取得或設定表單的輸入值
1.form.addEventListener('submit') 可以攔截送出動作
3.基本驗證可以用if來處理