Validate DateTime with FluentValidator

前端 未结 4 709
情书的邮戳
情书的邮戳 2020-12-31 02:25

This is my ViewModel class:

public class CreatePersonModel
{
    public string Name { get; set; }
    public DateTime DateBirth { get; set;          


        
相关标签:
4条回答
  • 2020-12-31 02:29

    As Stewart mentioned, it's not possible to use FluentValidation alone to get in front of the model binding in this way. I'd offer up two ideas/suggestions though:

    1. If you really can't change the ViewModel type from DateTime to string, you could always clear the model state yourself after model binding and then run the validator manually (I'm assuming you've wired FluentValidation to execute automatically after model binding).
    2. In scenarios like this, I would change the property to a string, but then use AutoMapper to map that into a DateTime for whatever business object / domain model / service contract request I need it to ultimately become. That way, you get the most flexibility with parsing and conversion on both sides of the model binding.
    0 讨论(0)
  • 2020-12-31 02:30
    public CreatePersonValidator()
    {
        RuleFor(courseOffering => courseOffering.StartDate)
           .Must(BeAValidDate).WithMessage("Start date is required");
    
        //....
    }
    
    private bool BeAValidDate(DateTime date)
    {
        return !date.Equals(default(DateTime));
    }
    
    0 讨论(0)
  • 2020-12-31 02:49

    Have a look at the Fluent Validation documentation on GitHub:

    https://github.com/JeremySkinner/FluentValidation/wiki

    Try adding a RegEx Validator to ensure that the user's input (a string) can be parsed as a date correctly, prior to applying the Less Than Validator.

    EDIT

    Having run few test cases and looked at the source code for Fluent Validator I concede that the above approach won't work.

    The standard error you get is added during the Model Binding phase, which happens before the fluent validation framework can access and check the model.

    I assumed that the framework's authors had been clever and were injecting their validation code into the model binding phase. Looks like they aren't.

    So the short answer is what you want to do does not appear to be possible.

    0 讨论(0)
  • 2020-12-31 02:49

    Try this one

    RuleFor(f =>
            f.StartDate).Cascade(CascadeMode.StopOnFirstFailure).NotEmpty()
                        .Must(date => date != default(DateTime))
                        .WithMessage("Start date is required");
    
    0 讨论(0)
提交回复
热议问题