特定于 .net C# 数据注释的 .NET 正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16796445/
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
.NET regex specific to .net C# dataannotations
提问by Chris Limina
I have a regular expression that i'm trying to figure out for a .NET Data Annotation Validation model that i'm using. Currently it looks like this
我有一个正则表达式,我正试图找出我正在使用的 .NET 数据注释验证模型。目前它看起来像这样
[RegularExpression("^((?!City)[a-zA-Z '])+$", ErrorMessage = "City is required and must be properly formatted.")]
The first half of this regex is to account for City, the second half is to make sure its only letters and spaces.
这个正则表达式的前半部分是考虑 City,后半部分是确保它只有字母和空格。
The default value for the input text box is City, so just "City" cant pass validation. I can't seem to get the first section of that regex to have these cases pass.
输入文本框的默认值是城市,所以只有“城市”不能通过验证。我似乎无法让正则表达式的第一部分通过这些案例。
Cityville
City City
Jersey City
Arizona City
But this case not pass:
但这种情况没有通过:
City
Any help would be greatly appreciated.
任何帮助将不胜感激。
*EDIT*This one did the trick:
*编辑*这个成功了:
^((?!^City$)[a-zA-Z '])+$
^((?!^City$)[a-zA-Z '])+$
I updated all of my validation to include this. Just in case you want to see what i'm doing. Here if the code for the whole validation data model that i'm using. (updated with the correct regex)
我更新了所有验证以包含此内容。以防万一你想看看我在做什么。这里是我正在使用的整个验证数据模型的代码。(使用正确的正则表达式更新)
public class FormModel {
[Required(ErrorMessage = "First Name is a Required field.")]
[DataType(DataType.Text)]
[Display(Order = 1, Name = "FirstName")]
[RegularExpression("^((?!^First Name$)[a-zA-Z '])+$", ErrorMessage = "First name is required and must be properly formatted.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name is a Required field.")]
[DataType(DataType.Text)]
[Display(Order = 2, Name = "LastName")]
[RegularExpression("^((?!^Last Name$)[a-zA-Z '])+$", ErrorMessage = "Last name is required and must be properly formatted.")]
public string LastName { get; set; }
[Required(ErrorMessage = "Address is a Required field.")]
[DataType(DataType.Text)]
[Display(Order = 3, Name = "Address")]
[RegularExpression("^((?!^Address$)[0-9A-Za-z #.,])+$", ErrorMessage = "Address is required and must be properly formatted.")]
public string Address { get; set; }
[DataType(DataType.Text)]
[Display(Order = 4, Name = "Address2")]
public string Address2 { get; set; }
[Required(ErrorMessage = "City is a Required field.")]
[DataType(DataType.Text)]
[RegularExpression("^((?!^City$)[a-zA-Z '])+$", ErrorMessage = "City is required and must be properly formatted.")]
[Display(Order = 6, Name = "City")]
public string City { get; set; }
[Required( ErrorMessage = "State is a Required field." )]
[DataType( DataType.Text )]
[Display( Order = 7, Name = "State" )]
public IEnumerable<String> State { get; set; }
[Required( ErrorMessage = "Zip is a Required field." )]
[DataType( DataType.Text )]
[RegularExpression( "\d{5}",
ErrorMessage = "Zip Code is required and must be properly formatted.")]
[Display( Order = 8, Name = "Zip" )]
public String Zip { get; set; }
[Required( ErrorMessage = "Phone is a Required field." )]
[DataType( DataType.PhoneNumber )]
[RegularExpression( "^[01]?[- .]?\(?[2-9]\d{2}\)?[- .]?\d{3}[- .]?\d{4}$",
ErrorMessage = "Phone is required and must be properly formatted.")]
[Display( Order = 9, Name = "Phone" )]
public string Phone { get; set; }
[Required( ErrorMessage = "Email is a Required field." )]
[DataType( DataType.EmailAddress )]
[RegularExpression( "^[A-Za-z0-9._%+-]*@[A-Za-z0-9.-]*\.[A-Za-z0-9-]{2,}$",
ErrorMessage = "Email is required and must be properly formatted.")]
[Display( Order = 10, Name = "Email" )]
public string Email { get; set; }
采纳答案by Sridhar Voorakkara
Try this out for the regular expression -
^((?!^City$)[a-zA-Z '])+$
To do a negative check for "City", I have added a start (^) & end ($) characters to City.
I have tested it at http://regex101.com/r/bF4bZ3and it seems to work if I am understanding the requirement correctly.
试试这个正则表达式 -
^((?!^City$)[a-zA-Z '])+$
为了对“城市”进行否定检查,我在城市中添加了一个开始 (^) 和结束 ($) 字符。我已经在http://regex101.com/r/bF4bZ3 上对其进行了测试,如果我正确理解了要求,它似乎可以工作。
回答by Haney
This is actually a really small mistake on your part. Change your Regex to:
这实际上是您的一个非常小的错误。将您的正则表达式更改为:
^(?!^City$)[a-zA-Z ']+$
And you'll have the desired effect. Basically the + means one or more times, and since you had the WHOLE expression enclosed in brackets which were to occur one or more times, it would find the "City" match at any point in the string... This instead says, in English: Not "City", and letters and spaces or single quotes one or more times.
你会得到想要的效果。基本上 + 表示一次或多次,并且由于您将 WHOLE 表达式括在括号中,这些表达式将出现一次或多次,它会在字符串中的任何一点找到“城市”匹配......英语:不是“城市”,字母和空格或单引号一次或多次。
A good tool to test Regex is Regex Hero: http://regexhero.net/tester
测试 Regex 的一个好工具是 Regex Hero:http: //regexhero.net/tester
回答by Ahmed KRAIEM
(?!City)means CityZero Width Negative Lookahead, so, ^((?!City)[a-zA-Z '])+$means:
(?!City)意味着City零宽度负前瞻,因此,^((?!City)[a-zA-Z '])+$意味着:
- Contains only letters spaces and '
- Does not contain
City
- 仅包含字母空格和 '
- 不含
City
Here is how to disallow City:
以下是禁止的方法City:
//Regular Expression
//^(?!^\s*City\s*$)[a-zA-Z ']+$
//as a .Net string
string str = "^(?!^\s*City\s*$)[a-zA-Z ']+$"
回答by Hunter Lewis
Negative matching in regular expressions is generally a bad idea, it's just not designed that way. The best method would be to check against:
正则表达式中的负匹配通常是一个坏主意,它只是不是那样设计的。最好的方法是检查:
"^City$"
And negate the test. In this case you don't really have an option to do that.
并否定测试。在这种情况下,您实际上没有选择这样做。
You are really close, you just need to move your anchors into the negative lookahead, and give the string a min length.
你真的很接近,你只需要将你的锚点移动到负前瞻中,并给字符串一个最小长度。
(?!^City$)[-a-zA-Z ]{4,}
This will match anything that is 4 characters or more that is not "City".
这将匹配 4 个或更多字符的任何非“城市”。
Without the min length the "ity" in "City" will be a match which won't help you.
如果没有最小长度,“City”中的“ity”将是一个对您无济于事的匹配项。
You can reduce the min length to 3 by adding a look behind if you like.
如果您愿意,您可以通过添加向后查看来将最小长度减少到 3。
(?!^City$)[-a-zA-Z ]{3,}(?<!^City$)
回答by Richard
Other answers have given you the help with the regular expression that you requested. I'm going to comment on a slightly different aspect - the default value should be something meaningful, or nothing at all ("City" is a bad default value).
其他答案为您提供了有关您请求的正则表达式的帮助。我要评论一个稍微不同的方面——默认值应该是有意义的,或者根本没有(“城市”是一个不好的默认值)。
What you probably wanted to do was put placeholder text, which disappears as soon as you enter the textbox. You can do this with the Promptproperty of Displayattribute if you're using NET 4.5 - see this answerfor details.
您可能想要做的是放置占位符文本,它会在您输入文本框后立即消失。如果您使用的是 NET 4.5,您可以使用Display属性的Prompt属性执行此操作-有关详细信息,请参阅此答案。
Not using a fake default value means you can just use [Required]and the users will need to enter something, and stops you needing to keep track of what your fake default values are.
不使用虚假默认值意味着您可以使用[Required]并且用户需要输入一些东西,并且不需要跟踪您的虚假默认值是什么。
Just to throw another spanner in the works, "City" is a valid place name- there are two villages called City in Wales and an area in Zurich!
只是为了在工作中抛出另一个扳手,“城市”是一个有效的地名- 威尔士有两个名为城市的村庄和苏黎世的一个地区!

