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!