asp.net-mvc Mvc 验证正则表达式只有数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8839827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:41:09  来源:igfitidea点击:

Mvc validation regular expression only numbers?

asp.net-mvcasp.net-mvc-3model-view-controller

提问by Neo

I tried the following code for digits-only validation for a contact number validation in Mvc web app.

我在 Mvc Web 应用程序中尝试了以下代码,用于仅数字验证的联系人号码验证。

[RegularExpression(@"/(^\(\d{10})?)$/", ErrorMessage = "Please enter proper contact details.")]
[Required]
[Display(Name = "Contact No")]
public string ContactNo { get; set; }

But the validation expression is not working.

但是验证表达式不起作用。

For the contact number I want to only accept digits. It can be either a 10 digit mobile number or a land-line number.

对于联系电话,我只想接受数字。它可以是 10 位手机号码或固定电话号码。

采纳答案by Darin Dimitrov

/ /is javascript way to build a regular expression literal object. In .NET you should not use it.

/ /是 javascript 构建正则表达式文字对象的方法。在 .NET 中你不应该使用它。

Try the following:

请尝试以下操作:

@"^\((\d{10}?)\)$"

or if you want exactly 10 digits:

或者如果你想要正好 10 位数字:

@"^(\d{10})$"

回答by gdoron is supporting Monica

If don't have any restrictions other than numbers only, this should fit:

如果除了数字之外没有任何限制,这应该适合:

[RegularExpression(@"^\d+$", ErrorMessage = "Please enter proper contact details.")]
[Required]
[Display(Name = "Contact No")]
public string ContactNo { get; set; }

回答by NMathur

This worked for me:

这对我有用:

[RegularExpression(@"^[0-9]{10}", ErrorMessage = "Please enter proper contact details.")]