![](/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.