2014-08-31 134 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