Search code examples
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:

    • ^ - Start of string (not sure it is necessary, I think the regex is anchored by default, but please check)
    • (?!0+$) - A negative lookahead that checks if the whole string is not equal to 0 (or 0000)
    • [0-9]+ - 1 or more digits from 0 to 9 (note that it already does not allow empty string)
    • $ - End of string (same note as for ^)