Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create attribute for validation and change the parameter value

I need to get parameter in controller action and validate this parameter. For example:

public TestController
{
    public ActionResult TestMethod(int testParamFromUri)
    {
        //here is my validation
        if(testParamFromUri < 0)
        {
            throw new TestException();
        }
        if(testParamFromUri > 50)
        {
            testParamFromUri = 50;
        }

        //other code
    }
}

My question:

Is it possible to create attribute where I can do verification like in method above?

and then use this attribute:

public ActionResult TestMethod([TestVerification]int testParamFromUri)
like image 890
netwer Avatar asked Dec 30 '25 09:12

netwer


1 Answers

I don't think you can get the desired behavior as described based on this answer; because there is no good way to access the value for validation.

What you can do is use a Custom ModelValidator that will execute any custom validation you would like for a given model.

I couldn't find a good tutorial, but you can get the idea of the basic setup below.

Controller Code

public TestController
{
    public ActionResult TestMethod(ModelName model)
    {
        //This will be false if your ModelState validator fails.
        if(ModelState.IsValid)
        {
            ....
        }
    }
}

Model Code

public class ModelName
{
    public int testParamFromUri { get; set; }
}

Model Validator Code

public class ModelNameValidator : IModelValidator<ModelName>
{
    public ModelNameValidator()
    {
    }

    public IEnumerable<ModelValidationResult> Validate(ModelName model)
    {
        //here now my verification
        if(model.testParamFromUri < 0)
        {
            yield return new ModelValidationResult()
            {
                MemberName = "testParamFromUri",
                Message = "Model Error Message Here"
            };
        }
    }
}

Now, once all of that has been setup, you need to register the model validator so that it executes whenever that ViewModel is used. This is done in the Global.asax file.

Global.asax

ModelValidatorProviders.Providers.Add(new ModelNameValidator());

Also, depending on how complicated your validation is, you could just use a DataAnnotation on your newly created model and the ModelValidator wouldn't be necessary.

public class ModelName
{
    [Range(0, int.MaxValue, ErrorMessage="Error Message")]
    public int testParamFromUri { get; set; }
}
like image 131
drneel Avatar answered Jan 01 '26 21:01

drneel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!