0

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?

Paul
  • 12,359
  • 20
  • 64
  • 101

3 Answers3

3

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);
    }
}
Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
  • Thanks Mystere... I tried Fluent Validation on my class... It showed the erros(client validation) fine with NotEmpty() method.... But usign RuleFor(x => x.MyDate).GreaterThan(new DateTime(2010, 6, 21)).LessThan(new DateTime(2010, 12, 17)) it did not did the client validation... How can I show the validation message in that case? – Paul Dec 02 '11 at 20:38
  • @Paul - Yes, GreaterThan, LessThan, and Must do not have client validation equivelents. You can use .InclusiveBetween, and that should work client-side. – Erik Funkenbusch Dec 02 '11 at 22:06
  • 1
    Thanks... But now I did that : RuleFor(x => x.MyDate).InclusiveBetween(new DateTime(2010, 6, 21), new DateTime(2010, 12, 17)).WithMessage("Error"); And the error is fired always, no matter what date I choose... Any idea? – Paul Dec 03 '11 at 12:05
0

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 :)

shennyL
  • 2,764
  • 11
  • 41
  • 65
  • Note: The datepicker doesn't prevent you from typing in a date outside that range, it just disables dates in picker that are not in the range. Also, you have to implement the client-side validation manually. – Erik Funkenbusch Dec 02 '11 at 22:53
-1

You can implement IValidatableObject.

Community
  • 1
  • 1
jrummell
  • 42,637
  • 17
  • 112
  • 171