Smartboy
Smartboy

Reputation: 1006

Date comparison in asp.net mvc3 model

I have two fields in my model

  1. CreateDateTo
  2. CreateDateFrom

which renders like this

<b>Start Date</b>  @Html.EditorFor(model => model.AdvanceSearch.CreateDatefrom, new {  @class = "picker startDate" })

<b>End Date</b> @Html.EditorFor(model => model.AdvanceSearch.CreateDateto, new { @class = "picker endDate" })

I have a validation scenario that enddate should not be greater then start date, currently I am validating it by jquery

$.validator.addMethod("endDate", function (value, element) {
        var startDate = $('.startDate').val();
        return Date.parse(startDate) <= Date.parse(value);
    }, "* End date must be Equal/After start date");

I want to know that is there any way in MVC3 model validation to do this?

Upvotes: 0

Views: 3227

Answers (2)

Antarr Byrd
Antarr Byrd

Reputation: 26071

You need to create a custom validation against the model. You could put this in the controller after if(Model.IsValid)


if(Model.End<Model.StartDate)
   ....

But I would stick to javascript. It works on the clientside and does not hit the server. Unless you just need the added assurance.

Upvotes: 2

Nick
Nick

Reputation: 6588

I would say that you should not rely solely on Javascript unless you are in control of your client's browser in some sort of intranet application. If the app is public facing - make sure you have both client and server side validation.

Also, a cleaner way of implementing the server side validation inside your model object can be done with a custom validation attribute shown below. Your validation then becomes centralised and you do not have have to explicitly compare the dates in your controller.

public class MustBeGreaterThanAttribute : ValidationAttribute
{
    private readonly string _otherProperty;

    public MustBeGreaterThanAttribute(string otherProperty, string errorMessage) : base(errorMessage)
    {
        _otherProperty = otherProperty;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var otherProperty = validationContext.ObjectInstance.GetType().GetProperty(_otherProperty);
        var otherValue = otherProperty.GetValue(validationContext.ObjectInstance, null);
        var thisDateValue = Convert.ToDateTime(value);
        var otherDateValue = Convert.ToDateTime(otherValue);

        if (thisDateValue > otherDateValue)
        {
            return ValidationResult.Success;
        }

        return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
    }
}

This can then be applied to your model like so:

public class MyViewModel
{
    [MustBeGreaterThan("End", "Start date must be greater than End date")]
    public DateTime Start { get; set; }

    public DateTime End { get; set; }

    // more properties...
}

Upvotes: 6

Related Questions