You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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.
  • properties explicitly lists the allowed fields (this is optional but makes the schema clearer for future readers).
  • anyOf is the star here—it means at least one of the following conditions must be true:
    1. The name field exists, and its value is not null.
    2. The email field exists, and its value is not null.

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 anyOf only 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 anyOf condition uses required to ensure the field exists before checking its value). If you want to allow missing fields (instead of just null values), you can remove the required clauses—then a missing field won't trigger a failure for that condition.

内容的提问来源于stack exchange,提问作者Suraj Birdawade

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 19:08:02