【问题标题】:Regex to allow only numbers and $ symbol [closed]正则表达式只允许数字和 $ 符号 [关闭]
【发布时间】:2015-08-24 12:32:01
【问题描述】:

我有一个要求,用户只能在文本框中输入数字和$ 符号。不应允许任何其他内容,并且应显示警告消息。

【问题讨论】:

  • 谷歌html form validation。

标签: javascript html regex


【解决方案1】:
^[\d\$]+$

要在 HTML 输入验证中使用此正则表达式,请使用正则表达式

[\d\$]+

解释:

^ assert position at start of the string
[\d\$]+ match a single character present in the list below
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
\d match a digit [0-9]
\$ matches the character $ literally
$ assert position at end of the string

例子:

$(function(){
    $('#text').keyup(function(){
        val = $(this).val();
        res = val.match(/^[\d\$]+$/);
        if(res == null){
            alert("Enter only $ or numeric");
        }
    })
})

DEMO

【讨论】:

  • 如果 OP 的意图是使用带有 pattern 属性的 HTML5 验证功能,则 ^ 和 $ 是隐式的,不是必需的。
【解决方案2】:

试试下面的功能

function AllowNumbers(e, field) {
var val = field.value;
var re1 = /(^[0-9$]+)/g;

val = re1.exec(val);
if (val) {
    field.value = val[0];
} else {
    field.value = "";
}
}

并在文本框的键位上调用此函数

【讨论】:

  • 所以当用户输入一个无效字符的那一刻,您将清除他迄今为止输入的所有内容?为什么你有两个^?
  • 认为你的正则表达式有错字;第二个^ 应该在字符类中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多