【问题标题】:Allow minus sign only as first input仅允许减号作为第一个输入
【发布时间】:2019-04-04 14:30:08
【问题描述】:

我在我的数字输入中使用正则表达式以只允许数字和逗号,但现在我想添加负数的机会,这可以像这样text.replace(/[^0-9,-]/g, ''); 完成。

但是,我希望仅允许将减号作为第一个输入,以避免出现 1-3,7 之类的内容。

【问题讨论】:

  • ^-?\d+$ 用于整数,或者^-?[\,d]+$ 用于千位逗号。

标签: angularjs regex input numeric


【解决方案1】:

我建议在这里只使用字符串test(),并带有适当的正则表达式模式:

^-?\d{1,3}(?:,\d{3})*(?:\.\d+)?$

您可以简单地拒绝任何未能通过此正则表达式的输入。这比尝试替换输入更有意义,因为并非所有输入都可以挽救。

例子:

var pass1 = 123.456;
var pass2 = -999;
var pass3 = '123,456,789.888';
var fail = '1-3,7';
console.log(/^-?\d{1,3}(?:,\d{3})*(?:\.\d+)?$/.test(pass1));
console.log(/^-?\d{1,3}(?:,\d{3})*(?:\.\d+)?$/.test(pass2));
console.log(/^-?\d{1,3}(?:,\d{3})*(?:\.\d+)?$/.test(pass3));
console.log(/^-?\d{1,3}(?:,\d{3})*(?:\.\d+)?$/.test(fail));

模式作用的简要说明:

^                from the start of the string
    -?           match an optional negative sign
    \d{1,3}      match one to three digits
    (?:,\d{3})*  followed by a thousands term (, + 3 digits) zero or more times
    (?:\.\d+)?   followed by an optional decimal component
$                end of the string

【讨论】:

  • 我必须进行替换,因为这个正则表达式在一个条件内,与一个变量相关联,并且根据具体情况,它会略有不同。我现在使用的是valueMatch = text.replace(/[^0-9.]/g, '');,只允许数字和点,另一个允许数字和逗号;我试过text.replace(/^-?[^0-9,]/g, '');,但它拒绝将减号作为第一个输入,我只想接受减号作为第一个输入
  • 正如我在回答中提到的,这不是最好的方法。我投票赞成使用单个正则表达式模式来验证您的输入。不要费心去纠正别人的错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 2018-04-22
  • 1970-01-01
  • 2017-10-04
相关资源
最近更新 更多