ASP.NET Core MVC自定义验证比较日期
创始人
2024-09-15 09:30:38
0

要在ASP.NET Core MVC中进行自定义日期比较验证,可以通过创建自定义验证属性来实现。以下是一个示例代码:

首先,创建一个名为"DateCompareAttribute"的类,继承自"ValidationAttribute"。

using System;
using System.ComponentModel.DataAnnotations;

public class DateCompareAttribute : ValidationAttribute
{
    private readonly string _comparisonProperty;

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

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

        if (property == null)
        {
            throw new ArgumentException("比较属性名称无效");
        }

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

        if (value == null || comparisonValue == null)
        {
            return ValidationResult.Success;
        }

        if (!(value is DateTime) || !(comparisonValue is DateTime))
        {
            throw new ArgumentException("该属性只能用于DateTime类型的属性");
        }

        var date = (DateTime)value;
        var comparisonDate = (DateTime)comparisonValue;

        if (DateTime.Compare(date, comparisonDate) > 0)
        {
            return new ValidationResult(ErrorMessage);
        }

        return ValidationResult.Success;
    }
}

接下来,使用"DateCompareAttribute"来装饰需要进行日期比较验证的属性。

public class MyViewModel
{
    [Display(Name = "开始日期")]
    public DateTime StartDate { get; set; }

    [Display(Name = "结束日期")]
    [DateCompare("StartDate", ErrorMessage = "结束日期必须晚于开始日期")]
    public DateTime EndDate { get; set; }
}

在上述代码中,"EndDate"属性使用了"DateCompare"属性,并指定了需要比较的属性名称为"StartDate"。如果"EndDate"的值早于或等于"StartDate"的值,将返回指定的错误消息。

最后,在控制器中进行模型验证即可。

[HttpPost]
public IActionResult Create(MyViewModel model)
{
    if (ModelState.IsValid)
    {
        // 模型验证通过,执行其他逻辑
        return RedirectToAction("Index");
    }

    return View(model);
}

以上就是通过自定义验证属性实现ASP.NET Core MVC的日期比较验证的解决方法。

相关内容

热门资讯

透视辅助“打哈儿麻将辅助软件”... 您好:打哈儿麻将辅助软件这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的...
我来教教大家“闲来辅助神器下载... 我来教教大家“闲来辅助神器下载2022”先前有辅助开挂插件(的确有挂);无需打开直接搜索微信(136...
透视真的“中至窝龙辅助”素来有... 透视真的“中至窝龙辅助”素来有辅助开挂插件(揭秘有挂);无需打开直接搜索微信(136704302)咨...
透视软件“中至余干万能辅助器”... 透视软件“中至余干万能辅助器”先前有辅助开挂脚本(有挂工具) 了解更多开挂安装加(136704302...
透视真的“酷玩联盟破解版下载”... 透视真的“酷玩联盟破解版下载”素来有辅助工具(了解有挂);无需打开直接搜索加(薇:136704302...
一分钟快速了解“兴动海满辅助”... 您好:兴动海满辅助这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特别...
技术分享“赣牌圈控制牌型”本然... 技术分享“赣牌圈控制牌型”本然有开挂辅助器(有挂总结);无需打开直接搜索加薇136704302(咨询...
总算了解“pokemmo免费脚... 总算了解“pokemmo免费脚本”本然有开挂辅助软件(确实有挂);无需打开直接搜索加(薇:13670...
推荐攻略“兴动互娱修改器免费”... 推荐攻略“兴动互娱修改器免费”素来有辅助开挂软件(讲解有挂) 了解更多开挂安装加(136704302...
新手必备“陕西三代辅助”往昔有... 新手必备“陕西三代辅助”往昔有辅助安装(有挂猫腻) 了解更多开挂安装加(136704302)微信号陕...