MVC3 custom validation attribute for an "at least one is required" situation
- by Pricey
Hi I have found this answer already:
MVC3 Validation - Require One From Group
Which is fairly specific to the checking of group names and uses reflection.
My example is probably a bit simpler and I was just wondering if there was a simpler way to do it.
I have the below:
public class TimeInMinutesViewModel {
    private const short MINUTES_OR_SECONDS_MULTIPLIER = 60;
    //public string Label { get; set; }
    [Range(0,24, ErrorMessage = "Hours should be from 0 to 24")]
    public short Hours { get; set; }
    [Range(0,59, ErrorMessage = "Minutes should be from 0 to 59")]
    public short Minutes { get; set; }
    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    public short TimeInMinutes() {
        // total minutes should not be negative
        if (Hours <= 0 && Minutes <= 0) {
            return 0;
        }
        // multiplier operater treats the right hand side as an int not a short int 
        // so I am casting the result to a short even though both properties are already short int
        return (short)((Hours * MINUTES_OR_SECONDS_MULTIPLIER) + (Minutes * MINUTES_OR_SECONDS_MULTIPLIER));
    }
}
I want to add a validation attribute either to the Hours & Minutes properties or the class itself.. and the idea is to just make sure at least 1 of these properties (Hours OR minutes) has a value, server and client side validation using a custom validation attribute.
Does anyone have an example of this please?
Thanks