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?