开发者

.Net 3.5 MetadataType Ignored when using validator

开发者 https://www.devze.com 2023-01-11 10:05 出处:网络
I have read and searched this issue with the Enterprise Library Validation mechanism. This very simple forms application demonstrates the issue. The Metadata class is ignored by the validator. I am tr

I have read and searched this issue with the Enterprise Library Validation mechanism. This very simple forms application demonstrates the issue. The Metadata class is ignored by the validator. I am trying to use it in a MVC application with an Entity Framework.

This is in .NEt 3.5 using VS 2008 on XP SP3.

namespace ValidationTest
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

        string longname = "this is much too long to be a name";
        Customer2 cust = new Customer2(l开发者_开发百科ongname);

        ValidationResults r = Validation.Validate<Customer2>(cust);
        if (!r.IsValid)
        {
            throw new ArgumentException();
        }
    }
}


public partial class Customer2
{

    public string CustomerName;

    public Customer2(string name)
    {

        CustomerName = name;
    }

}

[MetadataType(typeof(CustMetadata))]
public partial class Customer2
{
}

public class CustMetadata
{
    [StringLengthValidator(0, 20)]
    public string CustomerName { get; set; }
}

}

They are both in the same file for presentation purposes. If I move the StringLengthAttribute to the main class it does work.

Any insight would be greatly appreciated.

Thanks


The issue you are seeing is that in the Customer2 class CustomerName is a field but in the CustMetadata class CustomerName is a property.

If you change CustMetadata to:

public class CustMetadata
{
    [StringLengthValidator(0, 20)]
    public string CustomerName;
}

then it works as expected.

The Validation Application Block uses both the MemberType and the Name when matching the MetaData.

0

精彩评论

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