我有一个输入字段,用户应该只用数字和一个单点/逗号填充,并且只能采用以下格式。
这应该发生 .on("input")
意思是当用户输入时它应该保护正确的输入格式。
错误的字符应该用空格替换。
格式示例:
1.000
1.281
21212.000
21212.810
不是这样的:
1.02.12
或
1919,201,00
两个数字 block 之间只有一个点。
这是我目前所拥有的:
正则表达式 1:
$("body").on("input", "#testId", function(){
this.value = this.value.replace(/[^0-9]/g,'');
});
正则表达式 2:
$("body").on("input", "#testId", function(){
this.value = this.value.replace(/[0-9]+\.+[0-9]{1,3}/g,'');
});
正则表达式 3:
$("body").on("input", "#testId", function(){
this.value = this.value.replace(/[0-9]+\.+[0-9]{1,3}/g,'');
});
我想我在 replace()
方法上做错了。
不幸的是,他们都没有像我想要的那样工作。感谢您的帮助。
这是 FIDDLE
应该在 IE11 中工作
最佳答案
你可以试试这个。确保您的输入类型是tel,这样您就可以在移动浏览器中使用数字键盘
const regex = /[^\d.]|\.(?=.*\.)/g;
const subst=``;
$('#testId').keyup(function(){
const str=this.value;
const result = str.replace(regex, subst);
this.value=result;
});
.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html>
<body>
<input id="testId" type="tel" />
</body>
</html>
关于javascript - 使用 Regex javascript/jquery 仅允许以下格式的数字和点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43088557/