是否可以使用Data Annotation属性来操作文本并在操作后返回新文本?数据注释来替换物业的价值?
例如,我想验证一个字符串属性是否有特殊字符或单词之间有多个空格,然后返回一个新字符串来替换原始属性的值。
如何使用数据注释?
是否可以使用Data Annotation属性来操作文本并在操作后返回新文本?数据注释来替换物业的价值?
例如,我想验证一个字符串属性是否有特殊字符或单词之间有多个空格,然后返回一个新字符串来替换原始属性的值。
如何使用数据注释?
这不是用数据注释,而只是一个属性。
所以通过这里已经讨论过多种方法是:
How to get and modify a property value through a custom Attribute? Change Attribute's parameter at runtime
要注意从验证到的子类的各种解决方案,这是有趣的“你不能”
Corak的建议是最好的方式来做到这一点。但是,您可以编写您的基类并使用反射,您可以对类型成员的内容执行任何操作。
有点晚回答(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);
}
}
这里是一个包,将可能有你期待什么: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
。
难道你不能只是在获取/设置部分? 'Property {get {return _Property.Replace(badChar,goodChar); }}' – Corak 2013-03-21 07:05:10
我认为更好的方法是DataBinder:http://stackoverflow.com/a/1734025/7720 – Romias 2017-04-13 20:17:48