SidC
SidC

Reputation: 3203

ASP.net TextBox Regular Expression Needed to include 2 Decimal Places

Good Evening All,

I have a textbox that needs to accept 14 digits plus 2 decimal places. Examples include:
12345678901234
12345678901234.94
.75

To this end, I have the following code:

<asp:TextBox ID="txtQuantity" runat="server" CssClass="txtBox textboxRight"
    MaxLength="14" Width="70px"></asp:TextBox>

<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
    ControlToValidate="txtQuantity" Display="Dynamic" ErrorMessage="Required "
    SetFocusOnError="True" ValidationGroup="vgItem"></asp:RequiredFieldValidator>
&nbsp;

<asp:RegularExpressionValidator ID="RangeValidator1" runat="server"
    ControlToValidate="txtQuantity" Display="Dynamic" 
    ErrorMessage="Invalid Quantity"
    ValidationExpression="^\d+(?:\.\d{0,2})?$" 
    SetFocusOnError="True"></asp:RegularExpressionValidator>

The MaxLength for this textbox is set to 14 as well. Can anyone guide me as to how to write the regex to accept a total of 14 digits and two decimal places?

Thanks, Sid

Upvotes: 0

Views: 7327

Answers (1)

Kevin Brock
Kevin Brock

Reputation: 8944

Eleven digits followed by (optionally) period and two more digits. This is the maximum that can fit in your field: ^\d{1,11}(?:\.\d\d)?$

If you want the user to be able to type 14 digits without any decimals or up to 11 digits with two decimals (and not allow just a single decimal digit), you could do this: ^(?:\d{1,14}|\d{1,11}\.\d\d)$

Upvotes: 4

Related Questions