Reputation: 133
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.
<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?
Upvotes: 0
Views: 1125
Reputation: 784998
You need to use \\.
in RegExp
object:
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,
Upvotes: 1