I have an object, lets say this:
public class Person{
[Range(1, 100)]
public int Id {get;set;}
[Required]
public string Name {get;set;}
}
As you can see the Id should atleast contain 1 and the name field is required.
I have this validation method:
private static void ValidateObject(Person obj){
var context = new ValidationContext(obj, serviceProvider: null, items: null);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(obj, context, results);
if (!isValid)
{
throw new InvalidOperationException(results.First().ErrorMessage);
}
}
If I leave the Name empty, it will throw an error. Correct!
If I leave the Id to 0, it will NOT throw an error. And this is what I can't figure out. The variable isValid is also true (should be false)
What am I doing wrong?
Try to adjust the call to Validator.TryValidateObject with an extra parameter called 'validateAllProperties' and set it to true. If you omit it or set it to false (default) not-required properties will not be validated.
private static void ValidateObject(Person obj){
var context = new ValidationContext(obj, serviceProvider: null, items: null);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(obj, context, results, true);
if (!isValid)
{
throw new InvalidOperationException(results.First().ErrorMessage);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With