2

In my MVC application I have the following ViewModel:

public class MyViewModel
{
   public int StartYear { get; set; }
   public int? StartMonth { get; set; }
   public int? StartDay { get; set; }

   public int? EndYear { get; set; }
   public int? EndMonth { get; set; }
   public int? EndDay { get; set; }

   [DateStart]
   public DateTime StartDate
   {
       get
       {
           return new DateTime(StartYear, StartMonth ?? 1, StartDay ?? 1);
       }
   }

   [DateEnd(DateStartProperty="StartDate")]
   public DateTime EndDate
   {
       get
       {
           return new DateTime(EndYear ?? DateTime.MaxValue.Year, EndMonth ?? 12, EndDay ?? 31);
       }
   }
 }

I do not use a calendar helper because I need the date in this format (there is a logic behind). Now I created my Custom Validation rule:

    public sealed class DateStartAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            DateTime dateStart = (DateTime)value;
            return (dateStart > DateTime.Now);
        }
    }

    public sealed class DateEndAttribute : ValidationAttribute
    {
        public string DateStartProperty { get; set; }
        public override bool IsValid(object value)
        {
            // Get Value of the DateStart property
            string dateStartString = HttpContext.Current.Request[DateStartProperty];
            DateTime dateEnd = (DateTime)value;
            DateTime dateStart = DateTime.Parse(dateStartString);

            // Meeting start time must be before the end time
            return dateStart < dateEnd;
        }
    }

The problem is that DateStartProperty (in this case StartDate) is not in the Request object since it is calculated after the form is posted to the server. Therefore the dateStartString is always null. How can I get the value of StartDate?

CiccioMiami
  • 8,028
  • 32
  • 90
  • 151

2 Answers2

1

You can either use reflection to get the other property as in this answer (which seems a bit hacky to me), or create a custom validation attribute for the class rather than a single property as discussed here.

Community
  • 1
  • 1
GazTheDestroyer
  • 20,722
  • 9
  • 70
  • 103
0

Try this plugin: http://docs.jquery.com/Plugins/Validation/multiplefields.

Hope this helps~

Shirley
  • 19
  • 4