2012-04-24 50 views
0

這是我當前的代碼它會刪除所有非數字字符,除了$,逗號和點從輸入時的用戶類型:輸入表單中的禁止字符?

<input type="text" id="price" name="price" onkeyup="updatePrice(this.value)"> 

function updatePrice(p) { 
    document.getElementById("price").value = p.replace(/[^0-9$.,]/g, ''); 
    } 

的問題是,它在鍵入之後刪除字符,因此,如果您鍵入你會在消失之前看到它一小會兒。 Keydown在輸入實際發生變化之前運行腳本並不好。

如何完全防止這些禁止出現在輸入中的字符?

+0

怎麼樣onkeypress事件? – Thilo 2012-04-24 06:05:49

+0

[javascript限制文本輸入字符](http://stackoverflow.com/questions/5534346/javascript-limit-text-input-characters) – Thilo 2012-04-24 06:06:48

+0

可能的重複只是記住,這將_not_禁止用戶實際發送它們到服務器,所以你將需要處理無效的輸入服務器端 – 2012-04-24 06:58:26

回答

1
  • 使用onblur在輸入失去焦點時執行驗證 - 用戶在輸入過程中不必知道這一點。
  • 用戶不必知道這一點 - 您可以在提交後執行驗證。
1

您可以使用keypress事件和blur事件的組合來驗證每個鍵和整個字符串。如果您將輸入type更改爲type="number",那麼用戶代理將負責確保該值在更現代的瀏覽器中適用於您的有效數字格式。

// on key press occurs before the text is added visually to the input field 
​document.getElementById('price').addEventListener('keypress', function(e) { 
    if(!String.fromCharCode(e.which).match(/[0-9$\.,]/)) { 
    e.preventDefault(); // not a valid character so cancel it 
    } 
}, false);​​​​​​​​​​​​​ 

// complete validation for the text that was entered on blur to update price 
document.getElementById('price').addEventListener('blur', function(e) { 
    var validated = parseFloat(this.value.replace(/[^0-9\.]g/, '')); 
    // ... use the validated string to do something 
}, false);