JSON Schema Validator Advanced Techniques for Power Users
Advanced JSON Schema Validator Techniques for Power Users Once you're comfortable with basic validation, these advanced techniques will help you handle complex validation scenarios and integrate validation deeply into your systems. 1. Conditional Validation with if/then/else The most powerful feature in modern JSON Schema is conditional validation. Use it to enforce different rules based on the data itself: { "type" : "object" , "properties" : { "type" : { "type" : "string" , "enum" : [ "individual" , "business" ] }, "taxId" : { "type" : "string" }, "businessName" : { "type" : "string" } }, "allOf" : [ { "if" : { "properties" : { "type" : { "const" : "business" } } }, "then" : { "required" : [ "taxId" , "businessName" ] }, "else" : { "properties" : { "taxId" : { "not" : {} }, "businessName" : { "not" : {} } } } } ] } This schema makes taxId and businessName required only when type is "business". For individual accounts, those fields must not be present. 2. Custom Error Messages with Error Message Extension Enhance validation with user-friendly error messages that guide users toward correct input: { "type" : "object" , "properties" : { "password" : { "type" : "string" , "minLength" : 8 , "pattern" : "^(?=.*[A-Z])(?=.*[0-9])" , "errorMessage" : { "minLength" : "Password must be at least 8 characters" , "pattern" : "Password must contain at least one uppercase letter and one number" } } } } While not part of the core JSON Schema spec, many validators (including AJV) support the errorMessage keyword for better user-facing error reporting. 3. Schema Composition with allOf, anyOf, and oneOf Combine multiple schemas to create sophisticated validation rules: { "allOf" : [ { "$ref" : "#/$defs/baseUser" }, { "$ref" : "#/$defs/withTimestamp" }, { "if" : { "properties" : { "role" : { "const" : "admin" } } }, "then" : { "$ref" : "#/$defs/adminPrivileges" } } ] } allOf: Data must match ALL sub-schemas (intersection) anyOf: Data must match AT LEAST ONE sub-schema (union) oneOf: Da