Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions src/NJsonSchema.Tests/Generation/AttributeGenerationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -299,5 +299,41 @@ public async Task When_dictionary_property_has_regex_attribute_then_regex_is_add
Assert.Null(schema.Properties["Versions"].Pattern);
Assert.NotNull(schema.Properties["Versions"].AdditionalPropertiesSchema.ActualSchema.Pattern);
}

public class ClassWithRequiredDateTimeProperties
{
[Required]
public DateTime RequiredDateTime { get; set; }

[Required]
public DateTimeOffset RequiredDateTimeOffset { get; set; }

#if NET6_0_OR_GREATER
[Required]
public DateOnly RequiredDateOnly { get; set; }

[Required]
public TimeOnly RequiredTimeOnly { get; set; }
#endif

[Required]
public string RequiredString { get; set; }
}

[Fact]
public void When_required_DateTime_then_MinLength_is_not_set()
{
// Act
var schema = NewtonsoftJsonSchemaGenerator.FromType<ClassWithRequiredDateTimeProperties>();

// Assert
Assert.Null(schema.Properties["RequiredDateTime"].MinLength);
Assert.Null(schema.Properties["RequiredDateTimeOffset"].MinLength);
#if NET6_0_OR_GREATER
Assert.Null(schema.Properties["RequiredDateOnly"].MinLength);
Assert.Null(schema.Properties["RequiredTimeOnly"].MinLength);
#endif
Assert.Equal(1, schema.Properties["RequiredString"].MinLength);
}
}
}
9 changes: 8 additions & 1 deletion src/NJsonSchema/Generation/JsonSchemaGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1205,7 +1205,8 @@ public void AddProperty(
if (hasRequiredAttribute &&
!propertyTypeDescription.IsEnum &&
propertyTypeDescription.Type == JsonObjectType.String &&
!requiredAttribute.TryGetPropertyValue("AllowEmptyStrings", false))
!requiredAttribute.TryGetPropertyValue("AllowEmptyStrings", false) &&
!IsDateTimeFormat(propertyTypeDescription.Format))
{
propertySchema.MinLength = 1;
}
Expand Down Expand Up @@ -1306,6 +1307,12 @@ public bool IsPropertyIgnoredBySettings(ContextualAccessorInfo accessorInfo)
return accessorInfo.GetAttributes(true).FirstAssignableToTypeNameOrDefault("DataMemberAttribute", TypeNameStyle.Name);
}

private static bool IsDateTimeFormat(string? format)
{
return format is JsonFormatStrings.DateTime or JsonFormatStrings.Date or JsonFormatStrings.Time
or JsonFormatStrings.Duration or JsonFormatStrings.TimeSpan;
}

private static bool HasDataContractAttribute(Type parentType)
{
return parentType.ToCachedType()
Expand Down