Understanding ValidationContext in DataAnnotations

喜欢而已 提交于 2019-12-03 04:51:56

The only thing that's wrong about your code is the instance object for your validation context. The instance does not need to be the value that's being validated. For Validator.ValidateProperty, yes, it does need to be the object that owns the property, but for Validator.ValidateValue, "this" is sufficient.

I wrote a validation helper class to do the setup; this lets me pass in arbitrary values from anywhere.

public class ValidationHelper
{
    private List<ValidationResult> m_validationResults = new List<ValidationResult>();
    private List<ValidationAttribute> m_validationAttributes = new List<ValidationAttribute>();

    public Tuple<bool, List<string>> ValidateDOB(DateTime? dob)
    {
        m_validationAttributes.Add(new CustomValidationAttribute(typeof(DateOfBirthValidator), "ValidateDateOfBirth"));
        bool result = Validator.TryValidateValue(dob, 
                             new ValidationContext(this, null, null), 
                             m_validationResults, 
                             m_validationAttributes);
        if (result)
        {
            return Tuple.Create(true, new List<string>());
        }
        List<string> errors = m_validationResults.Select(vr => vr.ErrorMessage).ToList();
        return Tuple.Create(false, errors);
    }
}

If you are validating properties that have the validation attributes on the property, it's a lot easier:

internal void Validate(T value)
{
    if (!m_Initializing && TrackChanges && !Entity.IsImmutable)
    {
        Validator.ValidateProperty(value, new ValidationContext(Entity, null, null) { MemberName = PropertyName ?? ModelName });
    }
}

"Entity" is a property of the current class that references the object that I want to validate. This lets me validate properties on other objects. If you're already inside the objct, "this" will again be sufficient.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!