2014-08-31 49 views
2

我有一个ASP.NET MVC应用程序。此应用程序包含一个表单,我需要进行多次正则表达式检查,根据问题应该有不同的错误。多个独立的正则表达式

有没有人知道我会去分离错误的方式?我曾尝试在一个模型属性上使用多个RegularExpression注释,但这会在编译时引发错误。下面是代码的样本:

[Required] 
[Display(Name = "Distribution List Name")] 
[StringLength(65, ErrorMessage = "Must be under 65 characters")] 
[RegularExpression("^#(CONTOSO|MEGACORP|TESTCOMPANY)([-_A-Za-z0-9 ]+)$", ErrorMessage = "Invalid company, or the name contains invalid characters (Allowed characters are alphanumeric, - and _)")] 
public string Name { get; set; } 

理想情况下,我想在字符串的开始,为公司的检查,和允许的字符检查抛出单独的错误消息。

回答

2

2个选项,你可以考虑

一个。创建一个允许多次应用它的自定义属性(使用AllowMultiple=true)。

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple=true)] 
public class MyAttribute: RegularExpressionAttribute 
{ 
    .... 
} 

Global.asax.cs

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyAttribute), typeof(RegularExpressionAttributeAdapter)); 

注意注册,这是否与客户端验证

b口还没有测试。创建一个自定义验证器并分别测试每个正则表达式并返回相应的消息。

public class MyAttribute : ValidationAttribute, IClientValidatable 
{ 
    .... 
} 
+0

不要使用选项a.See这个http://stackoverflow.com/questions/35652533/should-i-use-multiple-regularexpression-attributes/35658502#35658502 – 2016-02-26 17:58:39

0

如果您不能对数据属性进行所有检查。 你可以做到这一点编程,当你做类似接收形式:

if(!myCheckIsOkay) 
    Modelstate.AddModelError("CompanyName", "the check of the company name was not correct") 
//... Do other checks 
if(Model.IsValid) 
//Do something here with valid model