9

i want a regular expression validator that will have numbers only till 10 digits

i have tried this but it is for only numbers and not for numbers of digit

<asp:RegularExpressionValidator ID="rvDigits" runat="server" ControlToValidate="txtMobId"
                                ErrorMessage="Enter numbers only till 10 digit" ValidationGroup="valGroup" ForeColor="Red"
                                ValidationExpression="\d+" />
2

2 Answers 2

16

You need to use a limiting quantifier {min,max}.

If you allow empty input, use {0,10} to match 0 to 10 digits:

ValidationExpression="^[0-9]{0,10}$"

Else, use {1,10} to allow 1 to 10 digits:

ValidationExpression="^[0-9]{1,10}$"

Or to match exactly 10-digit strings omit the min, part:

ValidationExpression="^[0-9]{10}$"

Also, note that server-side validation uses .NET regex syntax, and \d matches more than digits from 0 to 9 in this regex flavor, thus prefer [0-9]. See \d is less efficient than [0-9].

Besides, it seems you can omit ^ and $ altogether (see MSDN Regular Expressions in ASP.NET article):

You do not need to specify beginning of string and end of string matching characters (^ and $)—they are assumed. If you add them, it won't hurt (or change) anything—it's simply unnecessary.

Most people prefer to keep them explicit inside the pattern for clarity.

Sign up to request clarification or add additional context in comments.

3 Comments

My reading is the OP wants exactly 10 digits. You might want to include that in your answer too...
@Chris: I see only till 10 digits. I guess from ... till... ? Well, I added that case to the answer.
Yeah, its not exactly clear. My reading is "input numbers until you have 10 digits". The title also suggests 10 digits (and not less). Anyway, you've added it now. Thank you. :)
2

Test this answer:

<asp:RegularExpressionValidator ID="rvDigits" runat="server" ControlToValidate="txtMobId" ErrorMessage="Enter numbers only till 10 digit" ValidationGroup="valGroup" ForeColor="Red" ValidationExpression="[0-9]{10}" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.