Custom validation attribute with multiple instances problem

元气小坏坏 提交于 2019-12-01 17:31:23

问题


I'm using tha namespace System.ComponentModel.DataAnnotations in C# 4 to implement my own validation attribute and it looks like this

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class MyCustomValidator : ValidationAttribute {
    private String Property1 { get; set; }
    private String Property2 { get; set; }

    public ValeTaxiSituacaoRequired(String property1, String property2) {
        Property1 = property1;
        Property2 = property2;
    }

    public override bool IsValid(object value) {
        //validation logic
    }

}

I wanna use this attribute as below

[MyCustomValidator("Name", "Job")]
[MyCustomValidator("Name", "Email")]
[MyCustomValidator("Name", "Job")]
public class Employe {
}

The problem is that just one validation is perfomed. How can I execute all the validations (using asp.net mvc 2)?


回答1:


you have to override TypeId property http://www.paraesthesia.com/archive/2010/03/02/the-importance-of-typeid-in-asp.net-mvc-dataannotations-validation-attributes.aspx




回答2:


If you want to implement AllowMultiple=true on your own attribute then first override TypeID and next for solution to JQuery look at the article on code project here




回答3:


Take a look at FluentValidation. It allows you to separate your validation from the classes being validated so that you can call your validation logic at any time, on the server or the client.

It allows you to add as many rules of any complexity to a class, without cluttering it with attributes.



来源:https://stackoverflow.com/questions/3362886/custom-validation-attribute-with-multiple-instances-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!