I have a asp .net mvc application. For all my other attributes, I've used data annotations to verify the attributes. But I would like to have a custom validation. I was reading online that a custom data annotation validation may be the approach to take.
Following this link here ASP.NET MVC: Custom Validation by DataAnnotation it looks like a great solution. The only issue I'm coming across is how do I access my DBContext if it's not within a controller.
What I have so far
This is the code I typicalled used in controllers to grab the current user and db context.
Controller code
private ApplicationDbContext _dbContext => HttpContext.GetOwinContext().Get<ApplicationDbContext>();
private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
ViewModel
[HasNoRedemption]
public string code {get; set;}
HasNoRedemption.cs
public class HasNoRedemption : ValidationAttribute
{
public override bool IsValid(object value)
{
//check if user has ever claimed the code, return true is good
}
}
If I may get some assistance in making a custom validation such that I'll be able to check the db or a suggestion for a better approach.