I'm trying to use the System.ComponentModel.DataAnnotations classes to simplify data model validation, and I hit a roadblock. The Required attributes are working as expected for my class, but when I try MaxLength or StringLength, Validator.TryValidateObject() returns successfully. I'm stumped, after trying everything I can possibly think of.
Model Class
using System.ComponentModel.DataAnnotations;
public class MyClass
{
[Required]
[StringLength(3)]
//[MaxLength(3)] <===== This also yields the same result
public string? MyField { get; set; }
}
Test Class
Uses xunit and FluentAssertions
using System.ComponentModel.DataAnnotations;
using FluentAssertions;
using Xunit.Abstractions;
public class MyClassTests
{
[Fact]
public void MyFieldCantExceed50Characters()
{
var obj = new MyClass
{
MyField = "12345",
};
ICollection<ValidationResult> validationResults = new List<ValidationResult>();
var validated = Validator.TryValidateObject(obj, new ValidationContext(obj), validationResults);
validated.Should().BeFalse(); // <===== This assertion fails
}
}