2013-03-21 28 views
3

是否可以使用Data Annotation屬性來操作文本並在操作後返回新文本?數據註釋來替換物業的價值?

例如,我想驗證一個字符串屬性是否有特殊字符或單詞之間有多個空格,然後返回一個新字符串來替換原始屬性的值。

如何使用數據註釋?

+0

難道你不能只是在獲取/設置部分? 'Property {get {return _Property.Replace(badChar,goodChar); }}' – Corak 2013-03-21 07:05:10

+0

我認爲更好的方法是DataBinder:http://stackoverflow.com/a/1734025/7720 – Romias 2017-04-13 20:17:48

回答

1

Corak的建議是最好的方式來做到這一點。但是,您可以編寫您的基類並使用反射,您可以對類型成員的內容執行任何操作。

2

有點晚回答(2年!),但是可以修改在自定義DataAnnotations屬性中驗證的值。關鍵是壓倒一切ValidationAttribute的IsValid(Object, ValidationContext)方法以及執行小反射魔法:

public class MyCustomValidationAttribute : ValidationAttribute 
{ 
    protected override ValidationResult IsValid(object value, ValidationContext ctx) 
    { 
     // get the property 
     var prop = ctx.ObjectType.GetProperty(ctx.MemberName); 

     // get the current value (assuming it's a string property) 
     var oldVal = prop.GetValue(ctx.ObjectInstance) as string; 

     // create a new value, perhaps by manipulating the current one 
     var newVal = "???"; 

     // set the new value 
     prop.SetValue(ctx.ObjectInstance, newVal); 

     return base.IsValid(value, ctx); 
    } 
} 
0

這裏是一個包,將可能有你期待什麼:Dado.ComponentModel.Mutations

這個例子將確保無效字符從刪除一個字符串。它沒有引入驗證,但System.ComponentModel.Annotations可以與Dado.ComponentModel.Mutations一起使用。

public partial class ApplicationUser 
{ 
    [ToLower, RegexReplace(@"[^a-z0-9_]")] 
    public virtual string UserName { get; set; } 
} 

// Then to preform mutation 
var user = new ApplicationUser() { 
    UserName = "[email protected]_speed.01!" 
} 

new MutationContext<ApplicationUser>(user).Mutate(); 

調用Mutate()後,user.UserName將突變爲mx_speed01