C# 如何在json输入中验证集合日期时间的格式?
我知道如何使用注释验证特定格式的日期时间。 我知道如何验证DateTime集合(确保它们都有效) 我找不到如何验证在输入的json中,集合中的所有日期时间都是特定格式的 我需要验证在C# 如何在json输入中验证集合日期时间的格式?,c#,json,json.net,C#,Json,Json.net,我知道如何使用注释验证特定格式的日期时间。 我知道如何验证DateTime集合(确保它们都有效) 我找不到如何验证在输入的json中,集合中的所有日期时间都是特定格式的 我需要验证在DateTime的IList中,所有日期是否与格式“yyyy-MM-dd”匹配 我尝试了一个带有重写的IsValid函数的自定义类属性 不起作用,因为我接收到一个对象,它已经是一个可枚举的,并且已经为输入的json字符串转换了日期时间 json输入“DatesList:[“2012-10-01”,“2012-10”]
DateTime
的IList
中,所有日期是否与格式“yyyy-MM-dd”
匹配
我尝试了一个带有重写的IsValid
函数的自定义类属性
不起作用,因为我接收到一个对象,它已经是一个可枚举的
,并且已经为输入的json字符串转换了日期时间
json输入“DatesList:[“2012-10-01”,“2012-10”]
应该无效,但是“2012-10”
在我检查格式是否正确(在IsValid函数中)时,已经转换为值为2012-10-01
的日期时间
当我需要我的可重用属性用于检查json中所有输入的日期是否有效时,这里是json反序列化的目标类
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace XXX
{
/// <summary>
/// Handles a Forex Rate and its history
/// </summary>
public class FxRate : IExamplesProvider
{
/// <summary>
/// Base currency of the Forex Rate
/// </summary>
[Required]
[RegularExpression("^[a-zA-Z]{3}$", ErrorMessage = "bla")]
public string BaseCurrency { get; set; }
/// <summary>
/// Target currency of the Forex Rate
/// </summary>
[Required]
[RegularExpression("^[a-zA-Z]{3}$", ErrorMessage = "bla")]
public string TargetCurrency { get; set; }
/// <summary>
/// List of dates
/// </summary>
[Required]
[EnsureValidHistoryDates]
public IList<DateTime> Dates { get; set; }
}
}
使用Newtonsoft.Json;
使用制度;
使用System.Collections.Generic;
使用System.ComponentModel.DataAnnotations;
名称空间XXX
{
///
///处理外汇汇率及其历史记录
///
公共类FxRate:IExamplesProvider
{
///
///外汇汇率的基础货币
///
[必需]
[正则表达式(“^[a-zA-Z]{3}$”,ErrorMessage=“bla”)]
公共字符串BaseCurrency{get;set;}
///
///外汇汇率的目标货币
///
[必需]
[正则表达式(“^[a-zA-Z]{3}$”,ErrorMessage=“bla”)]
公共字符串TargetCurrency{get;set;}
///
///日期表
///
[必需]
[确保重新验证历史记录]
公共IList日期{get;set;}
}
}
然后我尝试使用属性函数:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class EnsureValidHistoryDatesAttribute : ValidationAttribute
{
private const string Format = "yyyy-MM-dd";
public override bool IsValid(object value)
{
var dateTimeConverter = new IsoDateTimeConverter { DateTimeFormat = Format };
IEnumerable<object> values = value as IEnumerable<object>;
// problem here, values is always null
if (values != null)
{
foreach (var val in values)
{
var obj = JsonConvert.DeserializeObject<DateTime>(val as string, dateTimeConverter);
if (obj == null)
{
return false;
}
}
}
var casted = value as IEnumerable<DateTime>;
if (casted != null)
{
var distCount = casted.Distinct().Count();
var count = casted.Count();
return count == distCount;
}
return false;
}
/// <summary>
/// Format error message
/// </summary>
/// <param name="name">name of the field</param>
/// <returns></returns>
public override string FormatErrorMessage(string name)
{
return string.Format(Resources.InvalidHistoryDates, name);
}
}
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
公共类EnsureValidHistoryDateAttribute:ValidationAttribute
{
私有常量字符串格式=“yyyy-MM-dd”;
公共覆盖布尔值有效(对象值)
{
var dateTimeConverter=new IsoDateTimeConverter{DateTimeFormat=Format};
IEnumerable values=作为IEnumerable的值;
//这里的问题是,值总是空的
如果(值!=null)
{
foreach(值中的var val)
{
var obj=JsonConvert.DeserializeObject(val作为字符串,dateTimeConverter);
if(obj==null)
{
返回false;
}
}
}
var casted=作为IEnumerable的值;
如果(铸造!=null)
{
var distCount=casted.Distinct().Count();
var count=casted.count();
返回计数==distCount;
}
返回false;
}
///
///格式错误消息
///
///字段名称
///
公共重写字符串FormatErrorMessage(字符串名称)
{
返回string.Format(Resources.InvalidHistoryDates,name);
}
}
任何使用属性注释验证T上具有特定格式的类型集合的通用方法都是非常受欢迎的,因为我被困在这里(我在google上尝试了很多不同的搜索)。List validDates=new List();
列表无效日期=新列表();
列表日期时间=新列表(){
"20181227",
"2018-12-27",
"27/12/2018",
"12/27/2018"
}; //不应该声明日期,应该有从JSON到字符串列表的转换
foreach(dateTimes中的字符串dateTime)
{
bool isValid=DateTime.TryParseExact(DateTime,“yyyy-MM-dd”,CultureInfo.InvariantCulture,datetimestyle.None,out-DateTime结果);
如果(有效)
{
有效期。添加(结果);
}
其他的
{
无效日期。添加(结果);
}
}
“验证在日期时间的IList中,所有日期是否与格式“yyyy-MM-dd”匹配?”(考虑澄清您实际回答的内容)是的,这段代码就是这么做的,然后OP知道如何处理结果谢谢你的回答,但我知道我的请求/方式不够清楚,无法描述我的问题。我知道如何验证日期或日期集合,我希望通过json输入的属性使用通用方法。我将尝试编辑我的原始帖子。
List<DateTime> validDates = new List<DateTime>();
List<DateTime> invalidDates = new List<DateTime>();
List<string> dateTimes = new List<string>() {
"20181227",
"2018-12-27",
"27/12/2018",
"12/27/2018"
}; //INSTEAD OF DECLARING THE DATES, THERE SHOULD BE THE CONVERSION FROM JSON TO STRINGS LIST
foreach(string dateTime in dateTimes)
{
bool isValid = DateTime.TryParseExact(dateTime, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime result);
if (isValid)
{
validDates.Add(result);
}
else
{
invalidDates.Add(result);
}
}