Reputation: 16365
I'm using Json.NET Schema .NET library.
Let's say I have defined a JSON schema like:
JSchema schema = JSchema.Parse(@"{
'type': 'object',
'required' : ['name'],
'properties': {
'name': {'type':'string'},
'roles': {'type': 'array'}
}
}");
Now I'm validating a JSON object (note that I'm not defining the name
property):
JObject user = JObject.Parse(@"{
'roles': ['Developer', 'Administrator']
}");
user.IsValid(schema, out IList<ValidationError> errors);
Debug.WriteLine(errors[0].ErrorType);
The output of the last line will be Required
. This way I know the specific error type at run time and I can make decisions according this error type programmatically.
My problem is that when I'm working with custom validations rules I'm not able to define a custom error type. So all my custom validators will create an error instance with the ErrorType
property equal to Validator
, like in the following example:
Defining a custom validation rule:
class MyCustomValidator : JsonValidator
{
public override void Validate(JToken value, JsonValidatorContext context)
{
var s = value.ToString();
if (s != "valid")
{
context.RaiseError($"Text '{s}' is not valid.");
}
}
public override bool CanValidate(JSchema schema)
{
return schema.Type == JSchemaType.String;
}
}
and running the validation using the custom validation rule:
JSchema schema = JSchema.Parse(@"{
'type': 'object',
'required' : ['name'],
'properties': {
'name': {'type':'string'},
'roles': {'type': 'array'}
}
}");
JObject user = JObject.Parse(@"{
'name': 'Ivalid',
'roles': ['Developer', 'Administrator']
}");
schema.Validators.Add(new MyCustomValidator()); // adding custom validation rule
user.IsValid(schema, out IList<ValidationError> errors);
Debug.WriteLine(errors[0].ErrorType);
The output will be Validator
.
My question is: Is there a workaround for this case? How can I differentiate the errors produced by my custom validation rules between them and from each other standard errors type?
Thanks!
Upvotes: 0
Views: 1141
Reputation: 16365
I received a feedback from the Json.NET Schema's author in a Github issue opened by me. The author says:
Hi
ErrorType is an enum so there isn't a way to define new values at runtime. You will need to embed the information about what the error is in the message and test the content.
That is: currently has no way to customize the error type property at runtime.
Upvotes: 1