My Software Notes

Useful things I discover

Archive for the ‘Data Validation’ Category

IValidatableObject for Complex Custom Validation

leave a comment »

Just a note to help me remember theĀ IValidatableObject interface that is used in ASP.NET MVC for adding complex custom validation to a view model.

You can put data annotations on a view model so when the data comes back from a request (e.g., a form post) and the data is being bound to the model, the data annotations can be used to validate that the data coming in is correct.

Example: the property on the view model is a string and you put theĀ StringLengthAttribute on it to specify that the length must be from 5 to 10 characters. If the value in the property is 12 characters then that will be caught and an entry will be added to the ModelState.

But what if your validation is complex? For example, you have property X that is a date that can’t be in the future and can’t be later than the date in property Y, but the date in property X is only required if the item has not been discontinued (a value of false in property Z).

You could write a custom data annotation, but it’s unlikely you’ll ever reuse it, so instead use the IValidatableObject interface. Ā Implement it on your view model and a Validate() method is added to your model that you can use to run your custom validations.

Rather than reinvent the wheel, here are some useful references on how to do it:



Written by gsdwriter

June 20, 2017 at 11:59 am