MVC 3 Custon Date Validation (Between two other Da

2019-09-04 12:12发布

问题:

I have a DateTime, and need to validate that ... I need that my DateTime stay Between two other Datetime (dynamic)...

How Can I do that?

回答1:

I like to use Fluent Validation. It gives you a lot more control over your validation.

With FluentValidation, you would do something like this (where MyDateTime, date1, and date2 are properties of your MyModel class) :

public class MyModelValidator : AbstractValidator<MyModel> {
    public MyValidator() {
        RuleFor(x => x.MyDateTime).InclusiveBetween(date1, date2);
    }
}


回答2:

Just declare a custom ValidationAttribute

   public sealed class Date1Attribute : ValidationAttribute
{
    public string date2Property { get; set; }
    public override bool IsValid(object value)
    {
        // Compare the date
        string date2String = HttpContext.Current.Request[date2Property];
        DateTime date1 = (DateTime)value;
        DateTime date2 = DateTime.Parse(date2String);

        return date1 >= date2;
    }
}

or if you are using a datepicker, you can restrict the minDate and maxDate like this:

   $('#date1').datepicker({
    constrainInput: true, 
    dateFormat: 'D, dd M yy',
    // Once change, set date2 min date
    onSelect: function (dateText, inst) {
        $('#date2').datepicker("option", "minDate", dateText);
       }
    });

   $('#date2').datepicker({
    constrainInput: true, 
    minDate: 0,
    dateFormat: 'D, dd M yy'
   });

Hope this help :)



回答3:

You can implement IValidatableObject.