Master
Master

Reputation: 2153

How to validate property on post

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.

Upvotes: 0

Views: 157

Answers (1)

Nicklaus Brain
Nicklaus Brain

Reputation: 929

1) I would not recommend using data annotation attributes to implement your business logic inside. Validation attributes are ought to contain pure functions. The intention behind the validation attributes is to narrow down the range of the input data that is considered to be correct. Not to implement business rules of your application

2) If you really wish to do what you want (for curiosity sake), check the following instructions: https://andrewlock.net/injecting-services-into-validationattributes-in-asp-net-core/

public class CustomValidationAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(
         object value, ValidationContext validationContext)
    {
        // validationContext.GetService() ... 
    }
}

Upvotes: 1

Related Questions