2010-06-28 150 views
2

在ASP.NET MVC 2中,我有一个Linq to sql类,它包含一系列字段。现在,当另一个字段具有某个(枚举)值时,我需要其中一个字段。基于其他领域的验证?

我已经走了这么远,我写了一个自定义验证属性,这可能需要一个枚举作为一个属性,但我不能说,例如:EnumValue = this.OtherField

我应该怎么办呢?

+0

我认为这种验证必须适用于类,而不是字段。 – Jay 2010-06-28 17:14:06

回答

4

MVC2附带一个示例“PropertiesMustMatchAttribute”,它显示了如何让DataAnnotations为您工作,它应该可以在.NET 3.5和.NET 4.0中工作。该样本代码如下所示:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] 
public sealed class PropertiesMustMatchAttribute : ValidationAttribute 
{ 
    private const string _defaultErrorMessage = "'{0}' and '{1}' do not match."; 

    private readonly object _typeId = new object(); 

    public PropertiesMustMatchAttribute(string originalProperty, string confirmProperty) 
     : base(_defaultErrorMessage) 
    { 
     OriginalProperty = originalProperty; 
     ConfirmProperty = confirmProperty; 
    } 

    public string ConfirmProperty 
    { 
     get; 
     private set; 
    } 

    public string OriginalProperty 
    { 
     get; 
     private set; 
    } 

    public override object TypeId 
    { 
     get 
     { 
      return _typeId; 
     } 
    } 

    public override string FormatErrorMessage(string name) 
    { 
     return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, 
      OriginalProperty, ConfirmProperty); 
    } 

    public override bool IsValid(object value) 
    { 
     PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value); 
     // ignore case for the following 
     object originalValue = properties.Find(OriginalProperty, true).GetValue(value); 
     object confirmValue = properties.Find(ConfirmProperty, true).GetValue(value); 
     return Object.Equals(originalValue, confirmValue); 
    } 
} 

当您使用属性,而不是把它放在你的模型类的属性,你把它的类本身:

[PropertiesMustMatch("NewPassword", "ConfirmPassword", ErrorMessage = "The new password and confirmation password do not match.")] 
public class ChangePasswordModel 
{ 
    public string NewPassword { get; set; } 
    public string ConfirmPassword { get; set; } 
} 

当“的IsValid “调用你的自定义属性,整个模型实例被传递给它,所以你可以通过这种方式获得相关的属性值。你可以很容易地遵循这种模式来创建一个更一般的比较属性。