开发者

Validation based on other field?

In 开发者_如何学JAVAASP.NET MVC 2, I have a Linq to sql class that contains a series of fields. Now I one of the fields is required when another field has a certain (enum) value.

I've come so far that I wrote a custom validation attribute, which can take an enum as an attribute, but I can't say, for example: EnumValue = this.OtherField

How should I do that?


MVC2 comes with a sample "PropertiesMustMatchAttribute" that shows how to get DataAnnotations to work for you and it should work in both .NET 3.5 and .NET 4.0. That sample code looks like this:

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

When you use that attribute, rather than put it on a property of your model class, you put it on the class itself:

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

When "IsValid" gets called on your custom attribute, the whole model instance is passed to it so you can get the dependent property values that way. You could easily follow this pattern to create even a more general comparison attribute.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜