基于其他领域的验证?

时间:2010-06-28 11:57:50

标签: c# asp.net-mvc-2 asp.net-mvc-2-validation

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

到目前为止,我写了一个自定义验证属性,它可以将枚举作为属性,但我不能说,例如:EnumValue = this.OtherField

我该怎么做?

1 个答案:

答案 0 :(得分:5)

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”时,会将整个模型实例传递给它,以便您可以通过这种方式获取依赖属性值。您可以轻松地遵循此模式来创建更一般的比较属性。