MVC 3 Custon Date Validation (Between two other Da

2019-09-04 12:26发布

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?

3条回答
smile是对你的礼貌
2楼-- · 2019-09-04 12:46

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);
    }
}
查看更多
何必那么认真
3楼-- · 2019-09-04 12:48

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

查看更多
一纸荒年 Trace。
4楼-- · 2019-09-04 13:06

You can implement IValidatableObject.

查看更多
登录 后发表回答