了解 DataAnnotations 中的 ValidationContext

发布于 2024-10-05 10:30:38 字数 821 浏览 0 评论 0原文

我想利用 Validator.TryValidateValue() ,但不了解其机制。比如说,我有以下内容:

public class User {
    [Required(AllowEmptyStrings = false)]
    [StringLength(6)]
    public string Name { get; set; }
}

方法:

public void CreateUser(string name) {...}

我的验证代码是:

ValidationAttribute[] attrs = bit of reflection here to populate from User class
var ctx = new ValidationContext(name, null, null);
var errors = new List<ValidationResult>();
bool valid = Validator.TryValidateValue(name, ctx, errors, attrs);

它工作正常,直到 name 的值为 null。我在实例化 ValidationContext 时收到 ArgumentNullException 并且不明白为什么。 TryValidateValue() 还要求非空上下文。我有一个值和一个属性列表来验证。 ValidationContext 是做什么用的?

I want to utilize Validator.TryValidateValue() but don't understand the mechanics. Say, i have the following:

public class User {
    [Required(AllowEmptyStrings = false)]
    [StringLength(6)]
    public string Name { get; set; }
}

and the method:

public void CreateUser(string name) {...}

My validation code is:

ValidationAttribute[] attrs = bit of reflection here to populate from User class
var ctx = new ValidationContext(name, null, null);
var errors = new List<ValidationResult>();
bool valid = Validator.TryValidateValue(name, ctx, errors, attrs);

It works fine until value of name is null. I'm getting ArgumentNullException when instantiating ValidationContext and don't understand why. TryValidateValue() also demands non-null context. I have a value and a list of attributes to validate against. What is that ValidationContext for?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吃素的狼 2024-10-12 10:30:38

您的代码唯一错误的是验证上下文的实例对象。该实例不需要是正在验证的值。对于 Validator.ValidateProperty,是的,它确实需要是拥有该属性的对象,但对于 Validator.ValidateValue,“this”就足够了。

我编写了一个验证辅助类来进行设置;这让我可以从任何地方传递任意值。

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);
    }
}

如果您要验证属性上具有验证属性的属性,则要容易得多:

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

“Entity”是引用我要验证的对象的当前类的属性。这让我可以验证其他对象的属性。如果你已经在对象内部,“this”就足够了。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文