MVC3自定义验证属性为"至少一个是必需的"情况

Pri*_*cey 1 c# validation asp.net-mvc-3

嗨,我已经找到了这个答案: MVC3验证 - 需要一个来自组

这对于检查组名并使用反射非常具体.

我的例子可能有点简单,我只是想知道是否有更简单的方法来做到这一点.

我有以下内容:

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

我想在"小时和分钟"属性或类本身中添加验证属性.我们的想法是确保这些属性中至少有一个(小时或分钟)具有值,服务器和客户端验证使用自定义验证属性.

有人有这方面的例子吗?

谢谢

Mat*_*cic 5

查看FluentValidation http://fluentvalidation.codeplex.com/或者您可以为每个ViewModel使用这个小助手,如果至少有一个属性有价值,或者根据需要进一步修改它.

public class OnePropertySpecifiedAttribute : ValidationAttribute
{       
    public override bool IsValid(object value)
    {            
         Type typeInfo = value.GetType();
         PropertyInfo[] propertyInfo = typeInfo.GetProperties();
         foreach (var property in propertyInfo)
         {
            if (null != property.GetValue(value, null))
            {                    
               return true;
            }
         }           
         return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

并将其应用于您的ViewModel:

[OnePropertySpecified(ErrorMessage="Either Hours or Minutes must be specified.")]
public class TimeInMinutesViewModel 
{
  //your code
}
Run Code Online (Sandbox Code Playgroud)

问候.