0

If I have a ViewModel class that is used as a property in other ViewModel classes. It has an editor template that renders dropdowns for day, month and year, and gets and sets a date value. I want to perform validation on this ViewModel in the classes it is used, and expose its date value for validation.

This would need to work for the RequiredAttribute class etc.

I can't seem to find a way to override the property/value used for validation. I imagined there would be something like there is for WebForms validation where you can decorate the class with the 'ValidationProperty' attribute.

Something like this:

[ValidationProperty("Value")]
public class DateViewModel
{
    public int Day{ get; set; }
    public int Month { get; set; }
    public int Year { get; set; }
    public DateTime? Value { get {...} }
}

public class PersonViewModel
{
    [Required(ErrorMessage = "Please specify your birth date")]
    public DateViewModel BirthDate { get; set; }
}

public class AdViewModel
{
    [Required(ErrorMessage = "Please specify an end date for your ad")]
    [SomeCustomValidation(ErrorMessage = "The ad end date must be in the future")]
    public DateViewModel EndDate { get; set; }
}
Jamie
  • 143
  • 8
  • What do you mean _perform validation outside of this class_? Show your models with the relevant annonations –  Feb 09 '15 at 00:59
  • You have it the wrong way around. The `[Required]` attribute needs to be on the `Value` property of `DateViewModel` if you want client and server side validation. –  Feb 09 '15 at 01:19
  • That is deliberate. I want to be able to re-use the view model for other non-birth date properties where they won't necessarily be required and might require other validation. – Jamie Feb 09 '15 at 01:30
  • The purpose of a view model is to include the properties specific to a view (i.e you should have 2 view models) but you model is never going to allow server side validation anyway. –  Feb 09 '15 at 01:33
  • "I'd like to be able to perform validation where this particular ViewModel class is used within another class." - As Stephen said, you shouldn't be doing this. – ChrisV Feb 09 '15 at 02:39
  • Correction - meant "in another ViewModel class". In this example, the "PersonViewModel" class is a view model containing first and last names, location, birth date etc. The "DateViewModel" is rendered in an editor containing dropdowns for the day, month and year values. With a "Value" property to (potentially) be validated. I was planning on reusing it in other situations where it may or may not be required and it might require a future or past date. Being able to expose a DateTime value for validation would help me handle the validation at a higher level. Or is this approach just plain wrong – Jamie Feb 09 '15 at 03:47

0 Answers0