如何解决.NET 5 迁移后自定义日期范围验证不会删除时间
我从 here 获得的这个自定义验证器在将我们的项目迁移到 .NET 5 后不起作用。它没有删除日期的时间部分。
public class DateAttribute : RangeAttribute
{
public DateAttribute(int min,int max)
: base(typeof(DateTime),DateTime.Now.AddYears(min).ToShortDateString(),DateTime.Now.AddYears(max).Date.ToShortDateString()) { }
}
[Required,DisplayName("Date")]
[Date(-2,ErrorMessage = "The Date should be within the last two years.")]
public DateTime Date { get; set; }
这是检查 html 输入时的样子:
<input type="date" value="2000-05-07" data-val="true" data-val-range="The Date should be within the last two years." data-val-range-max="04/12/2021 00:00:00" data-val-range-min="04/12/2019 00:00:00" data-val-required="The Date field is required." id="Date" name="Date">
我曾尝试使用 ToString("yyyy-MM-dd")、ToString("d"),并在 AddYears() 方法中对最小值和最大值进行硬编码,但发生了同样的事情。
之前在 .NET Core 3.1 上运行良好,直到 4 天前我们还在使用它。这是我能想到的唯一改变的东西。
有人有什么想法吗?
解决方法
我认为这是时区问题。时间出现时是否为一致值?例如,当我遇到这个问题时,时间总是说 5AM,因为它会从我的时区转换为 UTC(或相反)。
,您似乎只想在生成的 data-val-range-max
和 data-val-range-min
中显示日期,您需要更改自定义的 RangeAttribute,如下所示:
public class DateAttribute : RangeAttribute,IClientModelValidator
{
public int Min { get; set; }
public int Max { get; set; }
public DateAttribute(int min,int max)
: base(typeof(DateTime),DateTime.Now.AddYears(min).ToShortDateString(),DateTime.Now.AddYears(max).Date.ToShortDateString())
{
Min = min;
Max = max;
}
public void AddValidation(ClientModelValidationContext context)
{
context.Attributes.Add("data-val-range-max",DateTime.Now.AddYears(Max).ToShortDateString());
context.Attributes.Add("data-val-range-min",DateTime.Now.AddYears(Min).Date.ToShortDateString());
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。