From 13e203ae816dad618c464795c0ffc7767d560691 Mon Sep 17 00:00:00 2001 From: Marko Lahma Date: Sun, 8 Mar 2026 22:02:08 +0200 Subject: [PATCH] Skip StringLength attribute for date/time properties (#1373) Do not emit [StringLength] on properties with date-time, date, or time format, as the attribute is only meaningful for string types. Co-Authored-By: Claude Opus 4.6 --- .../ValidationAttributesTests.cs | 21 +++++++++++++++++++ .../Models/PropertyModel.cs | 5 ++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/ValidationAttributesTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/ValidationAttributesTests.cs index 5c97d646c..b2c62e2a8 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/ValidationAttributesTests.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/ValidationAttributesTests.cs @@ -480,5 +480,26 @@ public async Task When_array_property_has_minitems_then_minlength_attribute_is_r Assert.Contains("[System.ComponentModel.DataAnnotations.MinLength(10)]\n" + " public System.Collections.Generic.ICollection Value { get; set; } = new System.Collections.ObjectModel.Collection();\n", code); } + + [Fact] + public async Task When_date_time_property_has_min_max_length_then_no_string_length_attribute_is_generated() + { + var json = @"{ + 'type': 'object', + 'properties': { + 'myDateTime': { + 'type': 'string', + 'format': 'date-time', + 'minLength': 1, + 'maxLength': 50 + } + } + }"; + var schema = await JsonSchema.FromJsonAsync(json); + var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco }); + var code = generator.GenerateFile(); + + Assert.DoesNotContain("StringLength", code); + } } } diff --git a/src/NJsonSchema.CodeGeneration.CSharp/Models/PropertyModel.cs b/src/NJsonSchema.CodeGeneration.CSharp/Models/PropertyModel.cs index 771167aed..840b3112d 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp/Models/PropertyModel.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp/Models/PropertyModel.cs @@ -224,7 +224,10 @@ public bool RenderStringLengthAttribute } return _property.ActualTypeSchema.Type.IsString() && - (_property.ActualSchema.MinLength.HasValue || _property.ActualSchema.MaxLength.HasValue); + (_property.ActualSchema.MinLength.HasValue || _property.ActualSchema.MaxLength.HasValue) && + _property.ActualSchema.Format is not JsonFormatStrings.DateTime + and not JsonFormatStrings.Date + and not JsonFormatStrings.Time; } }