Glad
Glad

Reputation: 147

ASP MVC / EF6 - Using Custom Validation with Generics

I would like to know if it may be possible to use a generic class with a Custom Validator I have made. Here is the original code of the Custom Validator :

public class UniqueLoginAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value,
              ValidationContext validationContext)
    {
        ErrorMessage = string.Format("The Username {0} is already used.", value.ToString());
        //Validation process
    }
}

I would like to have something like that instead :

public class UniqueLoginAttribute<T> : ValidationAttribute where T : IManage
{
    protected override ValidationResult IsValid(object value,
              ValidationContext validationContext)
    {
        ErrorMessage = string.Format("The Username {0} is already used.", value.ToString())
        //EDIT
        new T().DoSomething();
        //End of Validation process
    }
}



The question is, how can I use such a Custom validator with one of my models ? Is it even possible ? Here is what I would like to achieve :

public class UserModel : IManage
{
    public int ID { get; set; }

    [UniqueLogin<UserModel>]
    public string UserName { get; set; }

    public int Age { get; set; }
}


Is there a way to use generics with that kind of custom validation ?

Upvotes: 0

Views: 1777

Answers (1)

Kris Vandermotten
Kris Vandermotten

Reputation: 10201

Generic attributes are not possible in C#, see also Why does C# forbid generic attribute types?

Here's a workaround:

public class UniqueLoginAttribute : ValidationAttribute
{
    public UniqueLoginAttribute(Type managerType)
    {
        this.ManagerType = managerType;
    }

    public Type ManagerType { get; private set; }

    protected override ValidationResult IsValid(object value,
          ValidationContext validationContext)
    {
        IManage manager = Activator.CreateInstance(this.ManagerType) as IManage;

        return manager.Validate(value);
    }
}

Usage:

[UniqueLoginAttribute(typeof(UserService))]

Upvotes: 1

Related Questions