Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement business and view validation without repeating code?

How do I avoid needing to repeat validation rules on both my ViewModels and business/domain objects?

For example I can use DataAnnotation attributes on my ViewModel, and this will give me client and server side validation in my MVC web app. But this ViewModel will then generally be mapped to a business/domain object and given to a service preform some business logic, meaning validation will have to happen again, often with the same or simular rules. Is there anyway round this?

like image 442
Dan Avatar asked Apr 19 '26 02:04

Dan


1 Answers

I think what you're describing is normal and acceptable. Consider your UI and data annotation as the friendly UI validation that is capable of showing users immediately any validation problems with the data entered.

I would consider your Business/Domain object's validation to be the complete validation, not just validating values but enforcing business rules (i.e. - Add Item to Cart -->Is the Item in Stock?)

Then there is always back end validation that is often enforced by the database (i.e. Allowing Nulls in a column). Unless your database allows nulls in all fields, your actually performing validation in more than just the two places you mentioned, and this I think is a good thing.

I think the bottom line is that you probably want your Business/Domain objects to enforce all validation, and your client side and back end validation to simply enforce the most basic.

Hope that helps.

like image 69
Jeff Reddy Avatar answered Apr 21 '26 05:04

Jeff Reddy



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!