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+" />
Liam
  • 27,717
  • 28
  • 128
  • 190
  • 1
    if you need a range up to 10 digits `\d{1,10}` – mnieto Jun 21 '16 at 10:40
  • 2
    Possibe Duplicate [Regular expression for 10 digit number without any special characters](http://stackoverflow.com/questions/4685500/regular-expression-for-10-digit-number-without-any-special-characters) – Rahul Hendawe Jun 21 '16 at 10:46

2 Answers2

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.

Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • My reading is the OP wants exactly 10 digits. You might want to include that in your answer too... – Chris Jun 21 '16 at 10:50
  • @Chris: I see *only **till** 10 digits*. I guess from ... till... ? Well, I added that case to the answer. – Wiktor Stribiżew Jun 21 '16 at 10:51
  • 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. :) – Chris Jun 21 '16 at 10:54
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}" />