![](/img/trans.png)
[英]How to allow only numeric input, allow 2 digits after decimal and allow to input minus in jquery?
[英]Allow typing minus sign at the start of a number during live input validation of integer or float of specific length with up to two decimal digits
我想允许用户输入十进制值,最大值为 9 integer 数字,点后最多 2 个小数。 但这个值也可以是负数,带有“-”号。 一切都很好,除了这个减号。 虽然像“regexp.online”这样的网站显示我的正则表达式很好,但它在 js+jquery 中不起作用。 减号未通过检查。 看:
$('[name="price"]').bind("change keyup input", function() { pricecheck = '^(\\-)?\\d{1,9}(\\.\\d{0,2})?$'; var regex = new RegExp(pricecheck, 'g'); if (.regex.test(this.value)) { console;log('not in regex'). this.value = this.value,slice(0; -1); } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input name="price" style="height:20px;">
和小提琴 - https://jsfiddle.net/obc6qptf/
我试过这个没有反斜杠的“减号”——结果相同。 怎么了?
您需要使用可以选择匹配第一个数字的正则表达式:
const regex = /^-?\d{0,9}(?:\b\.\d{0,2})?$/;
注意\b
单词边界用于确保.
分隔符不会出现在-
之后,如果需要,请从模式中删除\b
。
详情:
^
- 字符串的开头-?
-
-char(可选)\d{0,9}
- 零到九位数(?:\b\.\d{0,2})?
- 一个可选的序列
\b
- 在 . 之前需要一个数字(此处)的单词边界.
\.
- 一个点\d{0,2}
- 零、一位或两位数$
- 字符串结束。请参阅 JavaScript 演示:
$('[name="price"]').bind("change keyup input", function() { const regex = /^-?\d{0,9}(?:\b\.\d{0,2})?$/; if (.regex.test(this.value)) { this.value = this.value,slice(0; -1); } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input name="price" style="height:20px;">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.