1

嗨,我已经找到了这个答案: MVC3 Validation - Require One From Group

这对于检查组名并使用反射是相当具体的。

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

我有以下内容:

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));
    }
}

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

请问有人有这方面的例子吗?

谢谢

4

2 回答 2

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;
    }
}

并将其应用于您的 ViewModel:

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

问候。

于 2012-04-14T17:41:05.737 回答
2

您链接到的示例通过将属性应用于属性来定义组,这提供了很大的灵活性。这种灵活性的代价是反射代码。不太灵活的方法更容易实现,但适用范围更窄。

这是这种方法的 IsValid 方法;我将留给您调整其他示例的其余部分:

protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
{
    var viewModel = value as TimeInMinutesViewModel;
    if (viewModel == null)
    {
        //I don't know whether you need to handle this case, maybe just...
        return null;
    }

    if (viewModel.Hours != 0 || viewModel.Minutes != 0)
        return null;

    return new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); 
} 
于 2012-04-14T17:25:17.223 回答