Home > database >  StringLength validation always returns true
StringLength validation always returns true

Time:08-28

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
    }
}

CodePudding user response:

You need to set the validateAllProperties parameter to true. According to Microsoft:

true to validate all properties; if false, only required attributes are validated.

Your should call the method like so:

var validated = Validator.TryValidateObject(x, new ValidationContext(x), validationResults, true);

Another option is to use ValidateObject that will throw an exception if any requirement is not met.

Sources:

  • Related