javascript - 带警报的快速正则表达式

标签 javascript regex

我希望只允许数字和句点(但只有一个句点),没有逗号,没有字母。

因此用户可以输入 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/

相关文章:

xml - 如何使用 as3 删除 xml 标签

regex - 如何在 Google 文档文本编辑器中使用正则表达式查找和替换?

javascript - 在图表标签中显示计算的百分比

javascript - 如何将 php heredoc 转换为 javascript 变量?

javascript - 从事件获取文件时, typescript 对象可能为空

php - 如何修改此正则表达式以包含 https?

javascript - ng-show 和 ng-if 无法显示内容

javascript - 如何使用 MYSQL 和 jquery ajax 调用每 10 条记录浏览一次

正则表达式匹配 <A>、<BB>、<CCC> 但不匹配 <ABC> 等标签

python - 具有特定空白的大括号之前的字符串的正则表达式