我希望只允许数字和句点(但只有一个句点),没有逗号,没有字母。
因此用户可以输入 300.00
如果可能的话,我还需要触发警报(不是 Windows 警报,只是警报)
我有:
**<input maxlength="12" type="text" name="r" id="price" style="display:none;width:212px;margin-left:5px;border-color:#F12B63;" size="30" placeholder="Type your price numbers only" onkeyup="this.value = this.value.replace (/\D+/, '')" />**
最佳答案
对于正则表达式,请尝试以下操作:^\d+\.?\d+$
。
它将匹配以一位或多位数字开头的字符串,可选地后跟一个句点,然后后跟形成字符串结尾的一位或多位数字。
要测试该值,请在验证代码中执行以下操作:
//Add event handler using W3C event binding
document.getElementById("price").addEventListener("blur", function()
{
//Test the value of the input field and whether it matches the regular expression, where val is the value extracted from the field
if(!this.value.match(/^\d+\.?\d+$/))
{
alert("Validation error, must be numeric");
}
}, false);
编辑:请注意,如果您希望在 IE 中添加事件绑定(bind),您可以使用传统的事件绑定(bind) document.getElementById("price").onblur = function(){...}
或IE 的事件绑定(bind)模型: document.getElementById("price").attachEvent("onblur", function(){...});
请注意,使用 attachEvent
确实如此未在回调函数中分配 this 对象,因此您需要获取事件对象 (window.event
),然后使用 window.event.srcElement
提取元素。请参阅http://www.quirksmode.org/js/events_advanced.html供引用
关于javascript - 带警报的快速正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8935687/