我需要在使用.net的类中比较两个属性data annotations
。这两个属性之一应填写,另一个应为空白。如何覆盖的行为CompareAttribute
?如果不可能,替代解决方案是什么?
该类有一个问题:如果属性A设置为某项并且属性B已经具有值,则属性A会按预期变为无效。在属性B消隐后,属性A应该变为有效,但是直到我尝试修改属性A时它才生效,因此我再次触发了验证。有没有一种方法可以将两者连接在一起以触发对任一更改的验证?
class CustomAttribute : ValidationAttribute
{
private readonly string _other;
public CustomAttribute(string other)
{
_other = other;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var property = validationContext.ObjectType.GetProperty(_other);
if (property == null)
{
return new ValidationResult(
string.Format("Unknown property: {0}", _other)
);
}
var otherValue = property.GetValue(validationContext.ObjectInstance, null);
if (!String.IsNullOrEmpty(value.ToString()) && !String.IsNullOrEmpty(otherValue.ToString()))
{
return new ValidationResult("Test");
}
return null;
}
}
您可以CompareAttribute
使用自己的课程来扩展:
public class CustomCompareAttribute: CompareAttribute {
public CustomCompareAttribute(string otherProperty) : base(otherProperty) {
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
if (OtherProperty == null && value == null) {
return new ValidationResult("Either A or B should be filled");
}
// more checks here ...
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句