Problem: I am trying to manually Validate some c# objects, and the Validator is ignoring string length related validations.
Test Case: extending this example which uses the [Required] attribute, i also wanted to validate that strings were not too long, as follows.
public class Recipe
{
//[Required]
public string Name { get; set; }
[MaxLength(1)] public string difficulty = "a_string_that_is_too_long";
}
public static void Main(string[] args)
{
var recipe = new Recipe();
var context = new ValidationContext(recipe, serviceProvider: null, items: null);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(recipe, context, results);
if (!isValid)
{
foreach (var validationResult in results)
{
Console.WriteLine(validationResult.ErrorMessage);
}
} else {
Console.WriteLine("is valid");
}
}
Expected result: an error: "difficulty is too long."
Actual result: 'is valid'
other things tested:
You need to make 2 changes to have the validation work the way you expect:
1. You have to change the difficulty
field to a property.
The Validator
class only validates properties, so change the difficulty
definition to a property like this:
[MaxLength(1)] public string difficulty { get; set; } = "a_string_that_is_too_long";
2. Specify the validateAllProperties: true
parameter to the Validator.TryValidateObject
call.
The documentation for Validator.TryValidateObject
is not very forthcoming about the fact that, unless you use the overload with validateAllProperties: true
, only the Required
attribute will be checked. So modify the call like this:
var isValid = Validator.TryValidateObject(recipe,
context,
results,
validateAllProperties: true);
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