简体   繁体   中英

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.

                <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:

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,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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