Validator ignoring MaxLength attributes

Problem: I try to manually validate some C # objects, and the Validator ignores validations related to the length of the string.

Test case: Extending this example that uses the [Required] attribute, I also wanted to verify that the lines were not too long, as shown below.

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: Error: "Too much complexity."

Actual result: 'valid'

checked things:

+4
1

2 , , :

1. difficulty .

Validator , difficulty , :

[MaxLength(1)] public string difficulty { get; set; } = "a_string_that_is_too_long";

2. validateAllProperties: true Validator.TryValidateObject.

Validator.TryValidateObject , , validateAllProperties: true, Required . :

var isValid = Validator.TryValidateObject(recipe,
                                          context,
                                          results,
                                          validateAllProperties: true);
+4

Source: https://habr.com/ru/post/1690103/


All Articles