【问题标题】:Json Schema Date validaitonJson Schema 日期验证
【发布时间】:2016-07-25 01:37:00
【问题描述】:

我正在使用 JSON.Schema 验证我的负载。日期字段之一具有以下 json 架构。

    "Date": {            
        "type": "object",
        "properties": {
            "Value": {
                "type": "string",
                "format": "date"
            }
        },
        "required": [ "Value" ],
        "additionalProperties": false
    }

在我的服务器端(WEB API C#)我正在验证 json,如下所示。

var schema = JSchema.Parse(jsonSchema);
var livestockRow = JObject.Parse(jsonData);
IList<ValidationError> errorMessages;
livestockRow.IsValid(schema, out errorMessages);

我将我的日期传递为“24/09/2012”,它返回为以下错误:

String '24/09/2012' does not validate against format 'date'.

我错过了什么?

【问题讨论】:

    标签: c# .net json jsonschema json-schema-validator


    【解决方案1】:

    当指定"format": "date" 时,日期应采用yyyy-MM-dd 格式。

    如果您想针对其他格式对其进行验证,您可以定义自定义验证器:

    public class CustomDateValidator : JsonValidator
    {
        public override void Validate(JToken value, JsonValidatorContext context)
        {
            if (value.Type != JTokenType.String)
            {
                return;
            }
    
            var stringValue = value.ToString();
            DateTime date;
            if (!DateTime.TryParseExact(stringValue, "dd/MM/yyyy", CultureInfo.CurrentCulture, DateTimeStyles.None, out date))
            {
                context.RaiseError($"Text '{stringValue}' is not a valid date.");
            }
        }
    
        public override bool CanValidate(JSchema schema) => schema.Format == "custom-date";
    }
    

    在架构定义中使用它:"format": "custom-date" 和架构读取器设置:

    var schema = JSchema.Parse(jsonSchema, new JSchemaReaderSettings { Validators = new JsonValidator[] { new CustomDateValidator() } });
    

    【讨论】:

    • 我切换到 2021/02/20,它也不喜欢那样
    猜你喜欢
    • 1970-01-01
    • 2021-04-18
    • 2019-10-18
    • 2015-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    相关资源
    最近更新 更多