如何使用JSON Schema声明至少一个属性非空的校验规则?
How to Validate At Least One Non-Null Property in JSON Schema
Got it, let's work through this problem. Your goal is to make sure either name or email has a non-null value (they can both be non-null too). The schema you currently have only checks that both fields exist, not that their values aren't null—so we need to tweak it to target the actual value checks.
The Correct Schema Implementation
Here's a schema that will properly validate your personData and meet your requirements:
const personData = { name: null, email: 'test@gmail.com' }; const schema = { type: "object", properties: { name: {}, // Defines the field is allowed (no strict type enforced, accepts null or other values) email: {} }, anyOf: [ { properties: { name: { not: { type: "null" } } }, required: ["name"] // Ensure the field exists before checking its value }, { properties: { email: { not: { type: "null" } } }, required: ["email"] } ] };
How This Works
Let's break down the key parts:
type: "object"confirms we're validating an object structure.propertiesexplicitly lists the allowed fields (this is optional but makes the schema clearer for future readers).anyOfis the star here—it means at least one of the following conditions must be true:- The
namefield exists, and its value is not null. - The
emailfield exists, and its value is not null.
- The
Testing Your Example Data
Your personData has name: null but email: 'test@gmail.com'—this will pass validation because the second condition in anyOf is satisfied (email exists and isn't null).
Edge Cases Covered
- Both fields are non-null: Passes (since
anyOfonly needs one condition to be true, but both are valid here). - One field is non-null, the other is null: Passes.
- Both fields are null: Fails (neither condition is met).
- One field is missing entirely: Fails (each
anyOfcondition usesrequiredto ensure the field exists before checking its value). If you want to allow missing fields (instead of just null values), you can remove therequiredclauses—then a missing field won't trigger a failure for that condition.
内容的提问来源于stack exchange,提问作者Suraj Birdawade
相关产品推荐
相关产品推荐

