【问题标题】:Custom Validation for Dates uisng Fluent Validation使用 Fluentvalidation 对日期进行自定义验证
【发布时间】:2020-09-21 04:35:00
【问题描述】:

我需要一些关于使用 Fluent 验证的 loanStartDateloanEndDate 之间的日期的帮助。输入日期格式为字符串。我实际上想要针对特定​​场景的特定错误消息。

以下是我目前尝试的示例:

public class LoanSearchTypeValidator:> AbstractValidator<LoanSearchType>  
{  
    public LoanSearchTypeValidator() 
    {
        RuleFor(t => t.loanStartDate).Cascade(CascadeMode.Stop)
                                     .Must(BeValidateLoanDate);
            
        RuleFor(t => t.loanEndDate).Cascade(CascadeMode.Stop)
                                   .Must((date, obj) => BeValidateLoanEndDate)
                                   .When(k => !string.IsNullOrEmpty(k.loanStartDate);  
    } 
            
    private <bool > BeValidateLoanDate(string val)  
    {  
        var res = false;

        if (DateTime.TryParse(val, "yyyy-MM-dd", CultureInfo.InvariantCulture,> DateTimeStyle.None, out DateTime dt)  
        { 
            if(dt.Year >= 1900 && > dt.Year <= 2099)  
            {  
                res = true;  
            }  
            else  
            {  
                res = false; 
            } 
        }

        return res;  
    }  

    private <bool > BeValidateLoanEndDate(string enddt, string strtdt)  
    {  
        var res = false;

        if (DateTime.TryParse(enddt, "yyyy-MM-dd", CultureInfo.InvariantCulture,> DateTimeStyle.None, out DateTime end)  
        { 
            if (end.Year >= 1900 && > end.Year <= 2099)  
            {  
                res = true;  
            }  
            else  
            {  
                res = false; 
            }
        }    

        if (DateTime.TryParse(strtdt, "yyyy-MM-dd", CultureInfo.InvariantCulture,> DateTimeStyle.None, out DateTime start)
        {
            if (end > start)
            {
                res = true;
            }
            else
            {
                res = false;
            }
        }

        return res;  
    }
} 

Public class LoanSearchType
{
    public string loanStartDate { get; set; }
    public string loanEndDate { get; set; }
}

我需要诸如“日期格式错误”、“日期不在允许的年份范围内”、“结束日期不能早于开始日期”之类的消息。我需要你真诚的帮助。

【问题讨论】:

  • 您是否特别需要错误消息为“日期格式错误”、“日期不在允许的年份范围内”和“结束日期不能小于开始日期”?或者你需要注入日期吗? WithMessage 选项允许您为规则指定消息,并且它具有 lambda 重载来注入实例以验证属性。

标签: c# .net-core fluentvalidation


【解决方案1】:

您可以将PropertyValidatorContext context 传递给您的方法的参数,然后处理如下错误:

if(condition)
   context.MessageFormatter.AppendArgument("ValidationMessage", "First."); 
if(secondCondition)
   context.MessageFormatter.AppendArgument("ValidationMessage", "Second.");
if(anotherCondition)
   context.MessageFormatter.AppendArgument("ValidationMessage", "Another.");

【讨论】:

    猜你喜欢
    • 2015-12-04
    • 2022-11-09
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多