Where to put validation logic in MVC software architecture

I am really starting to learn mvc architecture.

I am confused as to whether to put the username login check logic in the model or in the controller.

I have some kind of status message that will tell the user whether the new username is available for registration or not.

My confusion started because most sources say that it should be in the model, because it includes username data for verification before putting it into the database (rather than checking input in the username field). However, the status message should respond immediately before changing the username field by clicking or changing the user, which made me think that it should be in the controller, because it is more associated with user events.

My problem is not what we use, but in the standard MVC concept. Where can I put the username verification logic based on the conditions / prerequisites above?

+4
source share
3 answers

As Shihar says, actually checking whether a name is acceptable / accessible is the responsibility of the model. A controller can provide an action that is invoked by some AJAX on the page, so that when each key is pressed, the text on the page is sent to the action of the dedicated controller, which then checks it through the model (everything related to the database, Model).

There are several things in a view, for example, when a user types, you must cancel previous calls before creating a new one, as this can be confusing.

Also, the controller’s act, which occurs when the user submits the form at the end of data entry, must perform the same check as the AJAX action to avoid race conditions between users.

+3
source

It should be in the model, as you read yourself. I think you are confused between the “verification process” and the “verification rules”. The verification process will either be in the client-side controller, but the verification rules are model properties.

+3
source

As a complement to @Colin Desmond, the model instance should never contain “incorrect” data, and, in my opinion, the MVC environment should contain validation logic. Thus, regardless of where the model instance is created, it can never be initialized with incorrect data, and classes that work with the model instance can rely on its data. An exception is the presence of validation logic, which depends on the type. Viewing dependent logic (exceptions) must be implemented in the controller.

For example, email address validation should be implemented in the model. However, the model may allow a bank transaction with a negative amount, but viewing A may not allow a transaction with a negative amount. The logic of this exception must be implemented on the controller.

0
source

Source: https://habr.com/ru/post/1380812/


All Articles