本文介绍了匹配以某些字符开头的任何字符串regex MVC DataAnnotations的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是MVC DataAnnotations中的正则表达式的新手.我有一个表单,其中有一个名为Option的字段.该选项必须以CA-开头.我以不同的方式编写了正则表达式以验证该字段,并且可以使其正常工作.我尝试了所有这些:
I new to Regular Expressions in MVC DataAnnotations. I have a form that has a field named Option. The option must start with CA-.I wrote the Regular Expression in different ways to validate this field and I can get it to work.I tried all this:
[RegularExpression(@"^CA-")]
[RegularExpression(@"/CA-/")]
[RegularExpression(@"^[C]+[A]+[-]")]
[RegularExpression(@"^CA-*")]
没有一项工作.我的代码有什么问题?谢谢.
none of this work.What is wrong with my code?Thank you.
public class CA_OptionsMetadata
{
[RegularExpression(@"^CA-", ErrorMessage = "The Option must start with CA-")]
[Required(ErrorMessage = "Option is Required")]
public string Option { get; set; }
//public string Cap_LBS { get; set; }
//public string Cap_KG { get; set; }
}
推荐答案
要在字符串的开头匹配 CA
,请使用
To match CA
at the beginning of a string, use
@"^CA-.*$"
主要要点是整个字符串应该匹配( RegularExpression
必需),因此.* $
很重要.
The main point is that the whole string should match (it is required by the RegularExpression
), thus .*$
is important.
正则表达式说明:
-
^
-字符串的开头 -
CA-
-文字CA-
字符序列 -
.*
-除换行符外的零个或多个字符 -
$
-字符串结尾
^
- start of stringCA-
- a literalCA-
sequence of characters.*
- zero or more characters other than a newline$
- end of string
这篇关于匹配以某些字符开头的任何字符串regex MVC DataAnnotations的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!