了解ValidationContext中的DataAnnotations [英] Understanding ValidationContext in DataAnnotations

查看:980
本文介绍了了解ValidationContext中的DataAnnotations的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想利用 Validator.TryValidateValue()但不明白的机制。说,我有以下几点:

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

和方法:

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

我的验证code是:

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

它正常工作,直到名称的值。我收到 ArgumentNullException 实例 ValidationContext ,不明白为什么当。 TryValidateValue()还要求非空的情况下。我有一个值和属性,以验证对的列表。那是什么 ValidationContext 的?

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?

推荐答案

唯一说的不对你的code是为您的验证环境的实例对象。实例并不需要是,正在被验证的值。对于Validator.ValidateProperty,是的,它确实需要拥有该属性的对象,但对于Validator.ValidateValue,这个就足够了。

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

实体是引用我想验证对象的当前类的属性。这让我对其他对象验证属性。如果您已经在objct内,本将再次就足够了。

"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.

这篇关于了解ValidationContext中的DataAnnotations的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆