简体   繁体   中英

How to apply Custom Validation rules to ViewModel attribute in MVC3

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 ?

您可以使用反射来获得该答案中的其他属性(对我来说似乎有点不客气),也可以为该类创建自定义验证属性,而不是为此处讨论的单个属性创建属性。

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

Hope this helps~

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM