I am using Newtonsoft.Json.Schema library and making use of custom validations to produce custom error messages, which are themselves defined in the schema.

"sku" : {
        "type" : "string", 
        "message" : {
                      "required" : "The SKU is a required field", 
                   }, 
         "format" : "Required"
 }

This works fine and I can pull the message from the given schema when the custom validation executes.

However I would like to add more custom validation like:

"sku" : {
        "type" : "string",
        "pattern" : "\d",
        "message" : {
                      "required" : "The SKU is a required field",
                      "pattern" : "The SKU must be a number" 
                   }, 
         "format" : "Pattern"  <--- can only specify a single custom validation
 }

Is there any way to get a second custom validator to run in order to get a custom validation for both required and pattern?

(Just to provide some background here... we have incoming data that must be validated but the errors need to be meaningful within the business context that the data originated from. That business context is unknown, so context sensitive messages, such as errors must be provided to the validation in some way).

1 Answers

0
robs On Best Solutions

So in the end I made a single custom validation which creates a new schema from the custom validation context like this:

JSchema valueSchema = JSchema.Parse(context.Schema.ToString() );

This creates a new schema just for the value being processed by the custom validation without any custom validation calls. A necessary step because the existing schema in context.Schema contains the call to the custom validation and we'll be stuck in an infinite loop without doing this.

Now I can run the value through this local schema and get a full report of all the errors that occur and deliver the relevant custom error message.

Custom error messages have property names that match the given ErrorType in the validation errors making the look up easy.