假设我有一个接口:
public interface ISomeInterface
{
bool SomeBool { get; set; }
string ValueIfSomeBool { get; set; }
}我有很多类可以实现这一点。即
public class ClassA : ISomeInterface
{
#region Implementation of ISomeInterface
public bool SomeBool { get; set; }
public string ValueIfSomeBool { get; set; }
#endregion
[NotNullValidator]
public string SomeOtherClassASpecificProp { get; set; }
}我在自定义验证器中对这个接口的属性有一个验证逻辑,如下所示:
public class SomeInterfaceValidator : Validator<ISomeInterface>
{
public SomeInterfaceValidator (string tag)
: base(string.Empty, tag)
{
}
protected override string DefaultMessageTemplate
{
get { throw new NotImplementedException(); }
}
protected override void DoValidate(ISomeInterface objectToValidate, object currentTarget, string key, ValidationResults validationResults)
{
if (objectToValidate.SomeBool &&
string.IsNullOrEmpty(objectToValidate.ValIfSomeBool))
{
validationResults.AddResult(new ValidationResult("ValIfSomeBool cannot be null or empty when SomeBool is TRUE", currentTarget, key, string.Empty, null));
}
if (!objectToValidate.SomeBool &&
!string.IsNullOrEmpty(objectToValidate.ValIfSomeBool))
{
validationResults.AddResult(new ValidationResult("ValIfSomeBool must be null when SomeBool is FALSE", currentTarget, key, string.Empty, null));
}
}
}我有一个属性来应用这个验证器,我用它来装饰ISomeInterface。
[AttributeUsage(AttributeTargets.Interface)]
internal class SomeInterfaceValidatorAttribute : ValidatorAttribute
{
protected override Validator DoCreateValidator(Type targetType)
{
return new SomeInterfaceValidator(this.Tag);
}
}当我调用Validation.Validate时,它似乎没有触发SomeInterfaceValidator中的验证。它执行特定于ClassA的验证,但不执行接口ISomeInterface的验证。
我怎么才能让这个起作用?
编辑:--我找到了一种让它工作的方法,那就是执行SelfValidation,在这里,我转换为ISomeInterface并像这样进行验证。这样就足够了,但问题仍然有待解决,看看是否还有其他方法来实现这一目标。
[SelfValidation]
public void DoValidate(ValidationResults results)
{
results.AddAllResults(Validation.Validate((ISomeInterface)this));
}发布于 2013-01-09 15:17:46
这是验证应用程序块的一个限制。这是一个描述如何为VAB添加Validator继承的文章。。
发布于 2013-01-10 00:11:52
验证接口的一种方法是使用ValidationFactory为接口创建一个Validator,而不是使用基于具体类型的Validator.Validate()静态外观或CreateValidator()。例如,考虑到您的方法,这应该是可行的:
var validator = ValidationFactory.CreateValidator<ISomeInterface>();
ValidationResults validationResults = validator.Validate(someInterfaceInstance);https://stackoverflow.com/questions/14237600
复制相似问题