Edition:
为了存档,我留下这个问题,但 tbh 我可能应该删除它。这完全是我的错,我做错了几件事。首先,我重用了 RequiredIf 验证中的代码,但我应该删除我忘记做的_innerAttribute和最内部的(如果与之相关(。最主要的是,我试图将枚举与字符串进行比较,这就是它失败的原因,但是如果我将适当的枚举成员传递给构造函数,代码实际上可以正常工作。我完全误解了物体的行为,演员...
版本结束
我正在尝试编写一个自定义验证属性,如果另一个字段不为 null,则不允许将字段设置为特定值。我已经写了这个(我省略了实现IClientVAlidatable的部分(
public class NotAllowedIfNotNullAttribute : ValidationAttribute, IClientValidatable
{
private readonly RequiredAttribute _innerAttribute = new RequiredAttribute();
public string DependentProperty { get; set; }
public object NotAllowedValue { get; set; }
public NotAllowedIfNotNullAttribute(string dependentProperty, object notAllowedValue)
{
DependentProperty = dependentProperty;
NotAllowedValue = notAllowedValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var typedValue = CastValue(value, _valueType)
;
var containerType = validationContext.ObjectInstance.GetType();
var field = containerType.GetProperty(DependentProperty);
if (field != null)
{
var dependentvalue = field.GetValue(validationContext.ObjectInstance, null);
if ((dependentvalue != null && value.Equals(NotAllowedValue)))
{
if (!_innerAttribute.IsValid(value))
return new ValidationResult(ErrorMessage, new[] { validationContext.MemberName });
}
}
return ValidationResult.Success;
}
//.....
}
我的问题value.Equals(NotAllowedValue)
,如何才能将值转换为 notAllowedValue 类型?我试图将类型作为参数传递,但我需要在这种方法上做更多工作,因为我暂时没有运气
谢谢!
也许你应该尝试使用模板?
public class NotAllowedIfNotNullAttribute<T> : ValidationAttribute, IClientValidatable
{
private readonly RequiredAttribute _innerAttribute = new RequiredAttribute();
public string DependentProperty { get; set; }
public T NotAllowedValue { get; set; }
public NotAllowedIfNotNullAttribute(string dependentProperty, T notAllowedValue)
{
DependentProperty = dependentProperty;
NotAllowedValue = notAllowedValue;
}
protected override ValidationResult IsValid(T value, ValidationContext validationContext)
...