Pass the Data to Custom Validation attribute in MVC C#

| By Webner

How to Pass the Data to Custom Validation attribute in MVC C#?


.Net provides the capability of validating model data with validation attributes like Required, Compare, Regular Expression, and user-defined custom attributes (also known as data annotations C#). MVC .net provides the built-in capability to verify the model data which can be validated at any time using TryValidateModel() method.

While implementing custom validation attributes, you may face the situation that along with the object instance property value, you may require some other information to calculate the validation result while validation checking in different scenarios (like CRUD operations).

Consider this situation where we want MyCustomAttribute validation check only at Update and Delete time but not during Add operation or in a different manner during the Add operation. Now the Model is validated from different actions or scenarios where you can control the validation based on extra information passing and processing by validation attribute.

Consider the following UserModel as an example –

Below is the sample structure of the implementation of validation attribute

The extra information in the validation attribute can be received through the items property of ValidationContext object instance which accepts the information in the dictionary object as key-value pairs.

For the implementation of validation context, Instead of simple TryValidateModel default approach, if extra information is to be passed, we would need to follow the validation call approach as follows:


Leave a Reply

Your email address will not be published. Required fields are marked *