ASP.NETCoreWebAPI-如何在EF中验证EndDate大于StartDate?
创始人
2024-09-18 08:01:15
0
  1. 在模型类中添加数据注解来验证EndDate大于StartDate。

示例代码:

public class MyModel { [Required] public DateTime StartDate { get; set; }

[Required]
[GreaterThan(nameof(StartDate), ErrorMessage = "EndDate must be greater than StartDate.")]
public DateTime EndDate { get; set; }

}

  1. 自定义数据注解来验证EndDate大于StartDate。

示例代码:

public class GreaterThanAttribute : ValidationAttribute { private readonly string _comparisonProperty;

public GreaterThanAttribute(string comparisonProperty)
{
    _comparisonProperty = comparisonProperty;
}

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
    var property = validationContext.ObjectType.GetProperty(_comparisonProperty);

    if (property == null)
    {
        return new ValidationResult($"Property {_comparisonProperty} not found.");
    }

    var comparisonValue = property.GetValue(validationContext.ObjectInstance, null);

    if (comparisonValue != null && value != null && (DateTime)value <= (DateTime)comparisonValue)
    {
        return new ValidationResult(ErrorMessage);
    }

    return ValidationResult.Success;
}

}

在模型类中使用自定义数据注解。

示例代码:

public class MyModel { [Required] public DateTime StartDate { get; set; }

[Required]
[GreaterThan(nameof(StartDate), ErrorMessage = "EndDate must be greater than StartDate.")]
public DateTime EndDate { get; set; }

}

然后,只需使用ModelState.IsValid来验证模型是否有效。

相关内容

热门资讯

往昔有辅助"边锋小程... 边锋小程序辅助免费开挂教程视频分享装挂详细步骤在当今的网络游戏中,边锋小程序辅助免费作为一种经典的娱...
原来有辅助!大唐山西辅助软件苹... 原来有辅助!大唐山西辅助软件苹果版(透视)德普之星怎么开辅助(攻略教程开挂辅助平台);无需打开直接搜...
原本有辅助"陕西辅助... 原本有辅助"陕西辅助"开挂(透视)辅助下载(扑克教程有挂秘笈);无需打开直接搜索加薇13670430...
传授开挂!开挂科技软件免费(透... 传授开挂!开挂科技软件免费(透视)aapoker真的假的(详细教程开挂辅助平台);无需打开直接搜索微...
从前有辅助"老友记 ... 从前有辅助"老友记 十三道辅助"开挂(透视)辅助软件(总结教程存在有挂) 【无需打开直接搜索加薇13...
正版开挂!传送屋辅助软件下载最... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
原生有辅助"潮汕掌上... 原生有辅助"潮汕掌上娱脚本"开挂(透视)辅助软件(必胜教程有人有挂)潮汕掌上娱脚本ai黑科技系统规律...
分享辅助!葫芦娃七子降妖内购破... 分享辅助!葫芦娃七子降妖内购破解版下载(透视)wepoker辅助视频(揭秘教程开挂辅助下载)【无需打...
素来有开挂"新圣游辅... 素来有开挂"新圣游辅助软件在哪下载"开挂(透视)辅助神器(总结教程有挂方法)>>您好:软件加薇136...
关于开挂!混沌休闲有没有挂(透... wepoker私人局透视插件是一款专注玩家量身打造的游戏记牌类型软件,在wepoker私人局透视插件...