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

C#中Newtonsoft Json Schema邮箱验证始终返回True的原因

问题原因及解决方案

核心原因

  1. 默认不启用format语义验证
    Newtonsoft.Json的传统JsonSchema类(对应Newtonsoft.Json.Schema包)默认仅验证结构类关键字(比如type),像format这类语义化的验证规则是默认关闭的,所以即使邮箱格式不符合要求,IsValid也会返回true。

  2. Schema存在语法错误
    你提供的schemaJson末尾多了两个多余的闭合大括号},这会导致Schema解析后的结构异常,虽然可能不会直接报错,但会影响验证逻辑的准确性。

修正步骤

1. 修复Schema语法错误

修正后的Schema JSON如下:

{
    "description": "A person",
    "type": "object",
    "properties": {
        "email": {"type":"string", "format":"email"},
        "name": {"type":"string"}
    }
}

2. 启用格式验证

在调用IsValid时,通过JsonSchemaValidationSettings开启ValidateFormat选项,代码示例:

string schemaJson = @"{
    'description': 'A person',
    'type': 'object',
    'properties': {
        'email': {'type':'string', 'format':'email'},
        'name': {'type':'string'}
    }
}";

JsonSchema schema = JsonSchema.Parse(schemaJson);

JObject person = JObject.Parse(@"{
    'email' : 'asdasd',
    'name': 'James'
}");

var validationSettings = new JsonSchemaValidationSettings
{
    ValidateFormat = true
};

bool valid = person.IsValid(schema, validationSettings);
// 此时valid会返回false,因为"asdasd"不符合邮箱格式

额外说明

注意Newtonsoft.Json.Schema包已被官方标记为过时,官方推荐使用后续替代库JsonSchema.Net,如果是新项目建议考虑迁移到该库以获得更好的支持。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 10:30:59