c# - 如何为 DateTime 验证添加范围

标签 c# asp.net-core blazor-server-side

我的 blazor 服务器端组件有一个简单的输入模型。我想对 DateTime 属性使用内置验证。

[Required]
public DateTime Date { get; set; }

我怎样才能只接受 DateTime 值 >= DateTime.Now?

最佳答案

您必须创建一个自定义验证属性。但是做的好,不像上面的答案那样……

using System;
using System.ComponentModel.DataAnnotations;

namespace YourAppNamespace
{
    public class FromNowAttribute : ValidationAttribute
    {
        public FromNowAttribute() {}

        public string GetErrorMessage() => "Date must be past now";

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var date = (DateTime)value;

            if (DateTime.Compare(date, DateTime.Now) < 0) return new ValidationResult(GetErrorMessage());
            else return ValidationResult.Success;
        }
    }
}

然后这样使用:

[Required]
[FromNow]
public DateTime Date { get; set; }

关于c# - 如何为 DateTime 验证添加范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62549258/

相关文章:

c# - 使用属性路由在 Controller 中获取操作的 url

azure - 消息未到达 Azure SignalR 服务

validation - 在 blazor razor 页面中使用 editform 时如何重置自定义验证错误

blazor - MudBlazor:单击“确定”按钮时防止关闭 MudDialog

c# 点对点编程(最好是去中心化的)

c# - 如何在automapper中映射内部类

c# - 类型转换错误

c# - 在 ASP.NET Core 6 中检查事件目录的跨平台方法

asp.net - GraphQL.NET 如何将枚举添加到 GraphQL 类型

带有 MessagePack 的 SignalR .Net 客户端 - IHubConnectionBuilder 中无法识别 AddMessagePackProtocol 方法