使用数据注释自定义模型验证依赖属性

时间:2010-02-17 12:30:51

标签: validation .net-3.5 asp.net-mvc-2 data-annotations

从现在开始我使用了优秀的FluentValidation 库来验证我的模型类。在Web应用程序中,我将它与jquery.validate插件结合使用,以执行客户端验证。 一个缺点是许多验证逻辑在客户端重复,不再集中在一个地方。

出于这个原因,我正在寻找替代方案。 many示例there显示了数据注释用于执行模型验证的用法。看起来很有希望。 我无法找到的一件事是如何验证依赖于另一个属性值的属性。

我们以下面的模型为例:

public class Event
{
    [Required]
    public DateTime? StartDate { get; set; }
    [Required]
    public DateTime? EndDate { get; set; }
}

我想确保EndDate大于StartDate。我可以写一个自定义 验证属性扩展ValidationAttribute以执行自定义验证逻辑。不幸的是我无法找到获得的方法 模型实例:

public class CustomValidationAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        // value represents the property value on which this attribute is applied
        // but how to obtain the object instance to which this property belongs?
        return true;
    }
}

我发现CustomValidationAttribute似乎完成了这项工作,因为它有ValidationContext属性,其中包含要验证的对象实例。不幸的是,此属性仅在.NET 4.0中添加。所以我的问题是:我可以在.NET 3.5 SP1中实现相同的功能吗?


更新:

ASP.NET MVC 2中似乎FluentValidation already supports客户端验证和元数据。

尽管数据注释可用于验证依赖属性,但仍然很好。

5 个答案:

答案 0 :(得分:29)

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);
        object originalValue = properties.Find(OriginalProperty, true /* ignoreCase */).GetValue(value);
        object confirmValue = properties.Find(ConfirmProperty, true /* ignoreCase */).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”时,会将整个模型实例传递给它,以便您可以通过这种方式获取依赖属性值。您可以轻松地按照此模式创建日期比较属性,甚至是更一般的比较属性。

Brad Wilson has a good example on his blog显示了如何添加验证的客户端部分,但我不确定该示例是否适用于.NET 3.5和.NET 4.0。

答案 1 :(得分:14)

我有这个问题,最近开源我的解决方案: http://foolproof.codeplex.com/

Foolproof对上述示例的解决方案是:

public class Event
{
    [Required]
    public DateTime? StartDate { get; set; }

    [Required]
    [GreaterThan("StartDate")]
    public DateTime? EndDate { get; set; }
}

答案 2 :(得分:7)

而不是PropertiesMustMatch可以在MVC3中使用的CompareAttribute。根据此链接http://devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-1

public class RegisterModel
{
    // skipped

    [Required]
    [ValidatePasswordLength]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }                       

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation do not match.")]
    public string ConfirmPassword { get; set; }
}
  

CompareAttribute 是一个新的,非常有用的验证器,实际上并非如此   部分   System.ComponentModel.DataAnnotations,   但已添加到   团队的System.Web.Mvc DLL。同时   没有特别好的名字(唯一的   比较它是检查   平等,所以也许E​​qualTo会   更明显),很容易看出来   此验证程序检查的用法   一个属性的值等于   另一个财产的价值。您可以   从代码中看,该属性   接受一个字符串属性   其他属性的名称   你在比较。经典用法   这类验证器就是我们的   正在使用它:密码   确认。

答案 3 :(得分:4)

自问题问题以来花了一些时间,但如果您仍然喜欢元数据(至少有时候),下面还有另一种替代解决方案,它允许您为属性提供各种逻辑表达式:

[Required]
public DateTime? StartDate { get; set; }    
[Required]
[AssertThat("StartDate != null && EndDate > StartDate")]
public DateTime? EndDate { get; set; }

它适用于服务器以及客户端。更多详情can be found here

答案 4 :(得分:3)

因为.NET 3.5的DataAnnotations的方法不允许您提供验证的实际对象或验证上下文,所以您必须做一些技巧才能完成此任务。我必须承认我不熟悉ASP.NET MVC,所以我不能说如何与MCV一起完成这个,但你可以尝试使用线程静态值来传递参数本身。这是一个可能有效的例子。

首先创建某种“对象范围”,允许您传递对象而不必通过调用堆栈传递它们:

public sealed class ContextScope : IDisposable 
{
    [ThreadStatic]
    private static object currentContext;

    public ContextScope(object context)
    {
        currentContext = context;
    }

    public static object CurrentContext
    {
        get { return context; }
    }

    public void Dispose()
    {
        currentContext = null;
    }
}

接下来,创建验证器以使用ContextScope:

public class CustomValidationAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
         Event e = (Event)ObjectContext.CurrentContext;

         // validate event here.
    }
}

最后但并非最不重要的是,确保对象通过ContextScope过去:

Event eventToValidate = [....];
using (var scope new ContextScope(eventToValidate))
{
    DataAnnotations.Validator.Validate(eventToValidate);
}

这有用吗?