Click or drag to resize
Json.NET Schema

Creating custom JSON validation rules with JsonValidator

 

This sample adds a custom validation rule to a JSchema using JsonValidator.

Sample
Types
public class CultureFormatValidator : JsonValidator
{
    public override void Validate(JToken value, JsonValidatorContext context)
    {
        if (value.Type == JTokenType.String)
        {
            string s = value.ToString();

            try
            {
                // test whether the string is a known culture, e.g. en-US, fr-FR
                new CultureInfo(s);
            }
            catch (CultureNotFoundException)
            {
                context.RaiseError($"Text '{s}' is not a valid culture name.");
            }
        }
    }

    public override bool CanValidate(JSchema schema)
    {
        // validator will run when a schema has a format of culture
        return (schema.Format == "culture");
    }
}
Usage
string json = @"[
  'en-US',
  'en-GB',
  'fr-FR',
  'purple monkey dishwasher',
  1234
]";

JSchemaReaderSettings settings = new JSchemaReaderSettings
{
    Validators = new List<JsonValidator> { new CultureFormatValidator() }
};

// the culture validator will be used to validate the array items
JSchema schema = JSchema.Parse(@"{
  'type': 'array',
  'items': {
    'type': 'string',
    'format': 'culture'
  }
}", settings);

JArray cultures = JArray.Parse(json);

IList<ValidationError> errors;
bool isValid = cultures.IsValid(schema, out errors);

// false
Console.WriteLine(isValid);

// Text 'purple monkey dishwasher' is not a valid culture name.
Console.WriteLine(errors[0].Message);

// Invalid type. Expected String but got Integer.
Console.WriteLine(errors[1].Message);