2013-02-12 158 views
8

我構建了一個自定義ValidationAttribute,因此我可以驗證系統中的唯一電子郵件地址。但是,我想傳遞一個自定義參數以添加更多邏輯到我的驗證。將自定義參數傳遞給ValidationAttribute

public class UniqueEmailAttribute : ValidationAttribute 
{ 
    public override bool IsValid(object value) 
    { 
     //I need the original value here so I won't validate if it hasn't changed. 
     return value != null && Validation.IsEmailUnique(value.ToString()); 
    } 
} 

回答

21

是這樣的嗎?

public class StringLengthValidatorNullable : ValidationAttribute 
{ 
    public int MinStringLength { get; set; } 
    public int MaxStringLength { get; set; } 

    public override bool IsValid(object value) 
    { 
     if (value == null) 
     { 
      return true; 
     } 
     var length = value.ToString().Length; 

     if (length < MinStringLength || length >= MaxStringLength) 
     { 
      return false; 
     } 
     return true; 
    } 
} 

用途:

[StringLengthValidatorNullable(MinStringLength = 1, MaxStringLength = 16)] 
public string Name {get; set;} 
+0

種類,但我只能通過這種方式傳遞常量,正確嗎?我想傳入原始值以與正在驗證的值進行比較。 – 2013-02-14 16:11:43

+0

是的,只有常數。我不確定我是否會收到您的問題。驗證器只能驗證一個屬性的當前值,它不知道任何屬性的過去值。 – Oliver 2013-02-14 16:19:33

+0

這就是我想要做的。 – 2013-02-14 16:50:36

0

我建議像@奧利弗的回答(這就是我會做,反正),但後來我發現,你不希望傳遞的常數。

那麼這樣的事情呢?

public static class MyConfig 
{ 
    public static int MinStringLength { get; set; } 
    public static int MaxStringLength { get; set; } 
    public static SomeObject otherConfigObject { get; set; } 
} 

然後從驗證中訪問MyConfig.MinStringLength? 雖然我會同意它不太漂亮。

1

有一個類似的要求,我必須將值傳遞給自定義屬性。

這裏的問題是,屬性裝飾不允許變量。 你得到編譯時錯誤:

An object reference is required for the non-static field, method, or property

這是我如何能做到這一點:

在控制器

[FineGrainAuthorization] 
public class SomeABCController : Controller 
{ 
    public int SomeId { get { return 1; } } 
} 

在屬性

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] 
public class FineGrainAuthorizationAttribute : AuthorizeAttribute 
{ 
    public override void OnAuthorization(AuthorizationContext filterContext) 
    { 
     base.OnAuthorization(filterContext); 
     ControllerBase callingController = filterContext.Controller; 
     var someIdProperty = callingController.GetType().GetProperties().Where(t => t.Name.Equals("SomeId")).First(); 
     int someId = (int) someIdProperty.GetValue(callingController, null); 
    } 
} 

請記住.Name.Equals("SomeId")內的字符串必須與聲明的大小寫匹配public int SomeId

相關問題