c# - 仅适用于 10 位数字和数字的正则表达式验证器 c# asp.net

标签 c# asp.net regex

我想要一个只有 10 位数字的正则表达式验证器

我已经试过了,但它只适用于数字而不是数字

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

最佳答案

您需要使用 limiting quantifier {min,max} .

如果允许空输入,使用{0,10}匹配0到10位数字:

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

否则,使用 {1,10} 允许 1 到 10 位数字:

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

或者要完全 匹配 10 位字符串,请省略 min, 部分:

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

另请注意,服务器端验证使用 .NET 正则表达式语法,并且 \d 匹配中的 09 中的多个数字这种正则表达式风格,因此更喜欢 [0-9]。参见 \d is less efficient than [0-9] .

此外,您似乎可以完全省略 ^$(参见 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.

为了清楚起见,大多数人更喜欢将它们显式地放在模式中。

关于c# - 仅适用于 10 位数字和数字的正则表达式验证器 c# asp.net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37942158/

相关文章:

c# - 使用模型作为参数将操作重定向到其他区域的操作

jquery - ASP.NET MVC - Ajax 将空值传递给 Controller

c# - 如何在C#中通过jquery赋值时获取文本框的值

asp.net - Javascript 文件被 chop

ruby-on-rails - 在 Ruby 字符串中查找和替换变量

php - preg_match 将 ALL 条件替换为 ANY

c# - 在 C# 项目中添加新的过滤器功能

c# - 表达式.Convert : Object of type 'System.Int64' cannot be converted to type 'System.Int32'

c# - 远程 Webdriver Chrome 抛出 "path to the driver executable"错误

.net - 前面匹配域名和获取视频 ID 时出现问题