2012-04-24 52 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);