Where to put validation logic in MVC software arch

2019-04-08 22:19发布

I am actually starting to learn the mvc architecture.

I'm confused on whether to place my username registration validation logic in model or in controller.

I have some sort of status message that would tell the user whether the new username to register is available or not.

My confusion started because most sources say that it should be in the model because it involves the username data to validate before placing it on the database (rather than checking inputs to the username field). However, the status message should respond immediately prior to the change in the username field by user keypress or change, which lead me to think that it should be in the controller because it involves more on user events.

My concern is not actually on the framework to use but on the standard concept involving MVC. Where do I put the username validation logic based on the conditions/premise above?

3条回答
对你真心纯属浪费
2楼-- · 2019-04-08 22:35

It should be in the model as you have read yourself. I think you are getting confused between the "validation process" and "validation rules". Validation process will either be in controller on the client side but validation rules are properties of model.

查看更多
甜甜的少女心
3楼-- · 2019-04-08 22:42

As an addition to @Colin Desmond, a model-instance should never contain 'wrong' data and thus, in my opinion, in an MVC environment should contain validation logic. So that, regardless of the place where an instance of the model is created, it can never be initialized with wrong data and classes that operate on the model instance can rely on its data. The exception is if there is validation logic that is view dependent. View dependent logic (exceptions) should be implemented in the controller.

For example, validation of an email-address should be implemented in the model. However, a model might allow a bank transaction with a negative amount, but view A might not allow a transaction with a negative amount. The logic for this exception should be implemented on the controller.

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-04-08 22:50

As Shikhar says, the actual checking of whether the name is acceptable/available is a Model responsibility. The controller can provide an action that is called by some AJAX on the page, so that as each key is pressed, the text on the page is sent to the dedicated controller action which then validates it through the model (anything that touches the database is Model).

There are a couple of things to consider in the view, such as when the user is typing quickly, you should cancel the previous calls before making the new one as this can get confusing.

Also the controller post action that happens when the user submits the form at the end of their data entry should perform the same validation as the AJAX action did just to avoid race conditions between users.

查看更多
登录 后发表回答