如何使用类验证属性动态设置属性上的验证消息
我正在编写位于类上的验证属性,但检查类的属性。我希望它在它发现无效的每个属性上设置验证消息。我该怎么做?
这是我到目前为止所得到的:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class LinkedFieldValidationAttribute : ValidationAttribute
{
private readonly string[] _properiesToValidate;
public LinkedFieldValidationAttribute(params string[] properiesToValidate)
{
_properiesToValidate = properiesToValidate;
}
public override bool IsValid(object value)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
foreach (var propertyName in _properiesToValidate)
{
var propertyValue = properties.Find(propertyName, false).GetValue(value);
//if value is invalid add message from base
}
//return validity
}
}
I'm writing Validation attribute that sits on the class but inspects the properties of the class. I want it to set a validation message on each of the properties it finds to be invalid. How do I do this?
This is what I have got so far:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class LinkedFieldValidationAttribute : ValidationAttribute
{
private readonly string[] _properiesToValidate;
public LinkedFieldValidationAttribute(params string[] properiesToValidate)
{
_properiesToValidate = properiesToValidate;
}
public override bool IsValid(object value)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
foreach (var propertyName in _properiesToValidate)
{
var propertyValue = properties.Find(propertyName, false).GetValue(value);
//if value is invalid add message from base
}
//return validity
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
IsValid
的另一个重载可以返回ValidationResult
< /a> 而不是bool
。Use the other overload of
IsValid
which can return aValidationResult
instead of abool
.