Skip to content

Commit

Permalink
✨ Expose failing JToken in ValidationError
Browse files Browse the repository at this point in the history
Exposing the JToken that failed the error will allow NJsonSchema to better leverage validation errors by accessing the value that failed the schema.
  • Loading branch information
ouvreboite committed Apr 12, 2024
1 parent 083501d commit 0e58408
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/NJsonSchema.Tests/Validation/ObjectValidationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public void When_token_is_not_object_then_validation_should_fail()

//// Assert
Assert.Equal(ValidationErrorKind.ObjectExpected, errors.First().Kind);
Assert.Equal("10", errors.First().Token?.ToString());
}

[Fact]
Expand All @@ -47,6 +48,7 @@ public void When_required_property_is_missing_then_it_should_be_in_error_list()
Assert.Equal("Foo", errors.First().Property);
Assert.Equal("#/Foo", errors.First().Path);
Assert.Equal(ValidationErrorKind.PropertyRequired, errors.First().Kind);
Assert.Equal("{}", errors.First().Token?.ToString());
}

[Fact]
Expand Down Expand Up @@ -134,6 +136,7 @@ public void When_string_property_required_but_integer_provided_then_it_should_fa
Assert.Equal(ValidationErrorKind.StringExpected, errors.First().Kind);
Assert.Equal("Foo", errors.First().Property);
Assert.Equal("#/Foo", errors.First().Path);
Assert.Equal("10", errors.First().Token?.ToString());
}

[Fact]
Expand Down Expand Up @@ -180,6 +183,7 @@ public void When_case_sensitive_and_property_has_different_casing_then_it_should

//// Assert
Assert.Equal(ValidationErrorKind.NoAdditionalPropertiesAllowed, errors.First().Kind);
Assert.Equal("\"foo\": 5", errors.First().Token?.ToString());
}

[Fact]
Expand Down
4 changes: 4 additions & 0 deletions src/NJsonSchema/Validation/ValidationError.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public ValidationError(ValidationErrorKind errorKind, string? propertyName, stri
Kind = errorKind;
Property = propertyName;
Path = propertyPath != null ? "#/" + propertyPath : "#";
Token = token;

var lineInfo = token as IJsonLineInfo;
HasLineInfo = lineInfo != null && lineInfo.HasLineInfo();
Expand Down Expand Up @@ -63,6 +64,9 @@ public ValidationError(ValidationErrorKind errorKind, string? propertyName, stri
/// <summary>Gets the schema element that contains the validation rule. </summary>
public JsonSchema Schema { get; private set; }

/// <summary>Gets the JToken of the element failed the validation. </summary>
public JToken? Token { get; private set; }

/// <summary>Returns a string that represents the current object.</summary>
/// <returns>A string that represents the current object.</returns>
/// <filterpriority>2</filterpriority>
Expand Down

0 comments on commit 0e58408

Please sign in to comment.