简体   繁体   English

允许在 integer 或特定长度的浮点数的实时输入验证期间在数字的开头键入减号,最多两位小数

[英]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

I want to allow user to input decimal value with maximim 9 integer digits, and maximum 2 decimals after dot.我想允许用户输入十进制值,最大值为 9 integer 数字,点后最多 2 个小数。 But also this value can be negative, with "-" sign.但这个值也可以是负数,带有“-”号。 Evereything is ok, except this minus sign.一切都很好,除了这个减号。 Though sites like "regexp.online" show that my regular expression is fine, it does no work in js+jquery.虽然像“regexp.online”这样的网站显示我的正则表达式很好,但它在 js+jquery 中不起作用。 Minus sign fails the checking.减号未通过检查。 See:看:

 $('[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;">

And fiddle - https://jsfiddle.net/obc6qptf/和小提琴 - https://jsfiddle.net/obc6qptf/

I tried this "minus" without backslashes - the same result.我试过这个没有反斜杠的“减号”——结果相同。 What is wrong?怎么了?

You need to use a regex that will match the first digit optionally:您需要使用可以选择匹配第一个数字的正则表达式:

const regex = /^-?\d{0,9}(?:\b\.\d{0,2})?$/;

Note the \b word boundary is used to make sure the .注意\b单词边界用于确保. separator does not come right after - , and if you need that, remove \b from the pattern.分隔符不会出现在-之后,如果需要,请从模式中删除\b

Details :详情

  • ^ - start of string ^ - 字符串的开头
  • -? - a - char (optional) - -char(可选)
  • \d{0,9} - zero to nine digits \d{0,9} - 零到九位数
  • (?:\b\.\d{0,2})? - an optional sequence of - 一个可选的序列
    • \b - a word boundary to require a digit (here) before . \b - 在 . 之前需要一个数字(此处)的单词边界.
    • \. - a dot - 一个点
    • \d{0,2} - zero, one or two digits \d{0,2} - 零、一位或两位数
  • $ - end of string. $ - 字符串结束。

See the JavaScript demo:请参阅 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM