Regular expression validator for 10 digit and numbers only c# asp.net
Solution 1
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.
Solution 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}" />
Related videos on Youtube
Admin
Updated on July 23, 2022Comments
-
Admin almost 2 years
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+" />
-
mnieto almost 8 yearsif you need a range up to 10 digits
\d{1,10}
-
Rahul Hendawe almost 8 yearsPossibe Duplicate Regular expression for 10 digit number without any special characters
-
-
Chris almost 8 yearsMy reading is the OP wants exactly 10 digits. You might want to include that in your answer too...
-
Wiktor Stribiżew almost 8 years@Chris: I see only till 10 digits. I guess from ... till... ? Well, I added that case to the answer.
-
Chris almost 8 yearsYeah, 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. :)