[英]Regex on JavaScript to accept only numbers with 2 decimals
I'm trying to do a Regex in a JavaScript + ASP.NET web form to validate a TextBox to accept only positive decimal numbers, with a max of 18 digits and 2 decimals. 我正在尝试在JavaScript + ASP.NET Web表单中进行正则表达式,以验证TextBox仅接受最大为18位和2个小数的正十进制数。
<script type="text/javascript">
$(document).ready(function (e) {
$("#<%=txtQtt.ClientID%>").bind('keypress', function (event) {
var regex = new RegExp("^[0-9]{1,18}(?:\.[0-9]{0,2})?$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
});
</script>
<span class="label100">Quantity:</span>
<asp:TextBox ID="txtQtt" runat="server" CssClass="txt200" MaxLength="20"></asp:TextBox>
The code "works"(its only accepting numbers), but not letting me type a dot, and I want to him only accept only one dot. 代码“有效”(它只接受数字),但不允许我键入一个点,而我希望他仅接受一个点。
What I'm doing wrong? 我做错了什么?
You need to use \\\\.
您需要使用\\\\.
in RegExp
object: 在RegExp
对象中:
var regex = new RegExp("^[0-9]{1,18}(?:\\.[0-9]{1,2})?$");
Or else you can use regex literal: 否则,您可以使用正则表达式文字:
var regex = /^[0-9]{1,18}(?:\.[0-9]{1,2})?$/
Also better to use [0-9]{1,2}
instead of [0-9]{0,2}
after decimal point otherwise it will also allow 123.
as valid number, 另外,最好在小数点后使用[0-9]{1,2}
而不是[0-9]{0,2}
,否则也可以使用123.
作为有效数字,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.