asp.netregexreg-expressionvalidator

Regular expression for reading positive integers with leading zeros


I have the following TextBox and RegularExpressionValidator

<asp:TextBox ID="txtQuantity" runat="server" MaxLength="7"></asp:TextBox>

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" 
runat="server" ErrorMessage="Enter only positive integer values."
ControlToValidate="txtQuantity" ValidationExpression="^[1-9][0-9]*$"
CssClass="required" Display="Dynamic" />

It is reading all the positive integers properly and giving error messages on wrong entries.

But validation is getting failed when a positive integer preceding with a 0 is entered.

Example: "098", "09" etc

Should I change my regular expression or the logic?


Solution

  • You can allow zeros with non-zeros and disallow just zeros (or empty string) with

    ^(?!0+$)[0-9]+$
    

    See demo

    REGEX EXPLANATION: