Skip to content

Commit

Permalink
Added check of RequiresValidationContext before calling IsValid (#110647
Browse files Browse the repository at this point in the history
)

* Added check of RequiresValidationContext before calling IsValid

The fix is done to avoid NRE when CompareAttribute's implementation of IsValid(object? value, ValidationContext validationContext) is called with validationContext == null.

Fix #42490

* Throw exception if validation context is null

* Unit test
  • Loading branch information
vvg88 authored Dec 24, 2024
1 parent 9c1bae3 commit bdf1143
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ public override string FormatErrorMessage(string name) =>
Justification = "The ctor is marked with RequiresUnreferencedCode informing the caller to preserve the other property.")]
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
ArgumentNullException.ThrowIfNull(validationContext);

var otherPropertyInfo = validationContext.ObjectType.GetRuntimeProperty(OtherProperty);
if (otherPropertyInfo == null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,15 @@ public static void Validate_PropertyHasDisplayName_UpdatesFormatErrorMessageToCo
Assert.Contains("CustomDisplayName", newErrorMessage);
}

[Fact]
public static void IsValid_ValidationContextNull_ThrowsArgumentNullException()
{
var attribute = new CompareAttribute(nameof(CompareObject.ComparePropertyWithDisplayName));
var compareObject = new CompareObject("test");

Assert.Throws<ArgumentNullException>(() => attribute.IsValid(compareObject.CompareProperty));
}

private class DerivedCompareAttribute : CompareAttribute
{
public DerivedCompareAttribute(string otherProperty) : base(otherProperty) { }
Expand Down

0 comments on commit bdf1143

Please sign in to comment.