function validateAmount(inputElement) {
let value = inputElement.value;
// 使用正規表示式匹配,允許開頭為可選的負號,然後是數字和小數點,最多兩位小數
const regex = /^-?\d+(\.\d{0,2})?$/;
if (!regex.test(value)) {
// 如果不匹配,則去除無效字元
inputElement.value = value.replace(/[^0-9.-]/g, '');
// 處理多個小數點的情況,只保留第一個
const decimalCount = (inputElement.value.match(/\./g) || []).length;
if (decimalCount > 1) {
inputElement.value = inputElement.value.replace(/\./g, (match, offset, string) => {
return offset === string.indexOf('.') ? '.' : '';
});
}
// 處理負號位置,只能在開頭
if (inputElement.value.startsWith('-') && inputElement.value.lastIndexOf('-') !== 0) {
inputElement.value = '-' + inputElement.value.replace(/-/g, '');
} else if (!inputElement.value.startsWith('-') && inputElement.value.includes('-')) {
inputElement.value = inputElement.value.replace(/-/g, '');
}
// 處理以小數點開頭的情況,前面加 0
if (inputElement.value.startsWith('.')) {
inputElement.value = '0' + inputElement.value;
}
// 處理負號和小數點一起開頭的情況,前面加 0
if (inputElement.value.startsWith('-.')) {
inputElement.value = '-0' + inputElement.value.substring(1);
}
// 限制小數位數
const parts = inputElement.value.split('.');
if (parts.length === 2 && parts[1].length > 2) {
inputElement.value = parts[0] + '.' + parts[1].substring(0, 2);
}
}
}
// 繫結input事件
const amountInput = document.getElementById('amountInput'); // 將 'amountInput' 替換為你輸入框的ID
if (amountInput) {
amountInput.addEventListener('input', function(event) {
validateAmount(this);
});
}
HTML示例:
<input type="text" id="amountInput" placeholder="請輸入金額">
程式碼解釋和改進:
-
正規表示式: 使用
^-?\d+(\.\d{0,2})?$
來匹配金額格式。^
: 匹配字串的開頭。-?
: 匹配可選的負號。\d+
: 匹配一個或多個數字。(\.\d{0,2})?
: 匹配可選的小數部分,最多兩位小數。$
: 匹配字串的結尾。
-
實時校驗: 使用
input
事件監聽輸入框的變化,並在每次輸入時進行校驗。 -
無效字元處理: 使用
replace(/[^0-9.-]/g, '')
去除任何非數字、小數點和負號的字元。 -
多個小數點處理: 程式碼現在可以處理多個小數點的情況,只保留第一個。
-
負號位置處理: 確保負號只能出現在開頭。
-
小數點開頭處理: 如果輸入以小數點開頭,則自動在前面新增
0
。 -
負號和小數點一起開頭處理: 如果輸入以
-.
開頭,則自動在前面新增0
。 -
小數位數限制: 限制小數部分最多隻能有兩位。
-
getElementById
的錯誤處理: 新增了if (amountInput)
來檢查是否找到了元素,避免空指標錯誤。
這個改進後的版本更加健壯,可以處理各種邊緣情況,並提供更好的使用者體驗。 它能實時響應使用者的輸入,並確保輸入框中的值始終符合金額格式的要求。