2013-03-21 53 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