Regex Javascript block Input



我刚刚用一个正则表达式控件构建了一个javascript函数,允许3个数字和一个点。

function restrictNumber(e) {
var newValue = this.value.replace(new RegExp(/^(?!^(?:d{1,3}|d(?:d?.d?|.d{2}))$).*/, 'gm'), "");
this.value = newValue;
}
$('.decimal').on('input', restrictNumber);
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<input class="decimal" type="text">

正则表达式的规格是:

  • max。3号
  • 只有一个或没有点
  • 点可以在任何地方

下面是它的正则表达式演示:https://regex101.com/r/3Ru1O3/3/

我试图"阻止"当一个字符输入不合适时。但是当我尝试测试时,它删除了我的孔字符串。

我怎么能改变这种行为,我只是不能设置新的数字,使字符串不消失。

您没有说明您的实际需求,例如,如果在某个数位值上需要小数,等等。但是基于您现有的regex的功能,它绝对可以被缩短。

function restrictNumber(e) {
var newValue = this.value.replace(/[^d.]/, "").substr(0,4);
this.value = newValue;
}
$('.decimal').on('input', restrictNumber);
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<input class="decimal" type="text">

最新更新