Where is the best place to validate data which will be used by model. For example, think about registration form. We have some data which come from registration form. So where is the best place to verify this data.We should check every data by if statements or special validator class, and this means lots of coding, so i want to learn where is the place to do this.
In Controller? or Model?
Both? Because some of the data should be validated by other models?
If you are not sure about exact answer, please try to find possible advantages and disadvantages of both ways.
Validation is an important aspect in ASP.NET MVC applications. It is used to check whether the user input is valid. ASP.NET MVC provides a set of validation that is easy-to-use and at the same time, it is also a powerful way to check for errors and, if necessary, display messages to the user.
Validation is carried out using the jQuery Validation library. Generally, in webform based applications, we make use of JavaScript in order to do client side validations. In MVC, client side validation do not introduce any JavaScript in the code to carry out validation.
If you're validating data on server side, And your validation does not require application business logic (i.e you're not checking to see if the user has enough credit in his account), You should validate in the controller.
The source of the validation data should be in the model while the actual checking should probably be done at both the view level (perhaps with javascript or UI hints) and at the model level. Purists will suggest that the view should not be involved but I disagree.
Certainly not in the controller, its sole task should be just controlling the request/response and familarize model and view with each other. Do it in the business model. Not with a bunch of if-statements, but just using a for-loop and an abstract validation framework.
Validation in the view should only be done to improve user experience. In webapps the view is basically the HTML page. In that validation is only possible with Javascript which runs entirely at the client side. The client has full control over it, such as hacking/disabling it. Use JS validation only to improve user experience (i.e. quicker response, no flash of content). Still do the (same) validation in the server side for better robustness.
Putting validation in your models prevents you from having to repeat validation code in a bunch of controllers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With