【问题标题】:Regular expression validator for 10 digit and numbers only c# asp.net仅适用于 10 位数字和数字的正则表达式验证器 c# asp.net
【发布时间】:2016-06-21 10:38:36
【问题描述】:

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

我试过这个,但它只适用于数字而不是数字

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

【问题讨论】:

标签: c# asp.net regex


【解决方案1】:

您需要使用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):

您无需指定匹配字符(^$)的字符串开头和结尾 — 它们是假定的。 如果你添加它们,它不会伤害(或改变)任何东西——它完全没有必要。

为了清晰起见,大多数人更喜欢在模式中保持明确。

【讨论】:

  • 我的读数是 OP 正好需要 10 位数字。你可能也想在你的答案中包含它......
  • @Chris:我只看到直到 10 位数。我猜从……到……?好吧,我在答案中添加了那个案例。
  • 是的,不是很清楚。我的阅读是“输入数字,直到你有 10 位数字”。标题还建议 10 位数字(不少于)。无论如何,您现在已经添加了它。谢谢你。 :)
【解决方案2】:

测试这个答案:

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

【讨论】:

    猜你喜欢
    • 2011-12-26
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多