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来验证模型是否有效。

相关内容

热门资讯

WePoKe透视挂!红龙扑克模... WePoKe透视挂!红龙扑克模拟器,(aa poker)原来存在有挂(详细透视力荐教程),支持语音通...
透视免费(德州免费辅助神器ap... 透视免费(德州免费辅助神器app)wepokeai代打(详细辅助微扑克教程)本来真的有挂1、在德州免...
透视好友房(wepOkE)外挂... 透视好友房(wepOkE)外挂透明挂辅助代打(wepoke模拟器)一直存在有挂(详细透视攻略方法);...
wepokeai代打!德扑之星... wepokeai代打!德扑之星记分牌有什么用,(aa poker)真是真的有挂(详细辅助科技教程);...
透视数据(德州ai机器人)nz... 透视数据(德州ai机器人)nzt德州辅助(详细辅助切实教程)都是真的是有挂1、许多玩家不知道德州ai...
透视苹果版(wePoke)透视... 1、透视苹果版(wePoke)透视辅助安装(wepok软件透明挂)确实是有挂(详细透视高科技教程)(...
wpk辅助挂!德州辅助软件开发... wpk辅助挂!德州辅助软件开发定制,(wePOke)一向真的是有挂(详细辅助插件教程);wpk辅助挂...
透视辅助(微扑克ai辅助)微扑... 透视辅助(微扑克ai辅助)微扑克ai辅助器苹果版(详细辅助黑科技教程)一直存在有挂是一款可以让一直输...
透视中牌率(WePoke)外挂... 1、透视中牌率(WePoke)外挂透明挂辅助器(wepoke一定有挂)原生真的是有挂(详细透视202...
wepoke黑科技!轰趴大菠萝... wepoke黑科技!轰趴大菠萝辅助器,(wEpOke)起初存在有挂(详细透视透视教程);人气非常高,...