您可以使用 keypress 事件和 blur 事件的组合来验证每个键和整个字符串。如果您将输入更改为 be 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);
</p>