Json 架构日期验证
Json Schema Date validaiton
我正在使用 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'.
我错过了什么?
当指定 "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"
并在架构 reader 设置中使用它:
var schema = JSchema.Parse(jsonSchema, new JSchemaReaderSettings { Validators = new JsonValidator[] { new CustomDateValidator() } });
我正在使用 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'.
我错过了什么?
当指定 "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"
并在架构 reader 设置中使用它:
var schema = JSchema.Parse(jsonSchema, new JSchemaReaderSettings { Validators = new JsonValidator[] { new CustomDateValidator() } });