了解 DataAnnotations 中的 ValidationContext
我想利用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码唯一错误的是验证上下文的实例对象。该实例不需要是正在验证的值。对于 Validator.ValidateProperty,是的,它确实需要是拥有该属性的对象,但对于 Validator.ValidateValue,“this”就足够了。
我编写了一个验证辅助类来进行设置;这让我可以从任何地方传递任意值。
如果您要验证属性上具有验证属性的属性,则要容易得多:
“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.
If you are validating properties that have the validation attributes on the property, it's a lot easier:
"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.