简体   繁体   中英

Custom Validation for Dates uisng Fluent Validation

I want some help with date between loanStartDate and loanEndDate using Fluent Validation. The input date format is in string. I actually want specific error messages for specific scenarios.

Below is the example what I tried so far:

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; }
}

I need messages like "Date is in wrong format", "Date doesn't come within permissable year range", "end date cannot be less than start Date". I need you sincere help.

You can pass PropertyValidatorContext context to parameters of your method, then handle errors like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM