使用Fluent验证的日期的自定义验证

问题描述

我需要使用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,out DateTime end)  
        { 
            if (end.Year >= 1900 && > end.Year <= 2099)  
            {  
                res = true;  
            }  
            else  
            {  
                res = false; 
            }
        }    

        if (DateTime.TryParse(strtdt,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; }
}

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

解决方法

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

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