将验证逻辑放在MVC软件体系结构中的何处 [英] Where to put validation logic in MVC software architecture

查看:61
本文介绍了将验证逻辑放在MVC软件体系结构中的何处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实际上开始学习mvc架构.

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.

我所关心的实际上不是要使用的框架,而是涉及MVC的标准概念.根据上述条件/前提,我将用户名验证逻辑放在哪里?

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?

推荐答案

正如Shikhar所说,对名称是否可接受/可用进行实际检查是模型责任.控制器可以提供一个由页面上的某些AJAX调用的操作,以便在按下每个键时,页面上的文本将发送到专用的控制器操作,然后该控制器通过模型对其进行验证(任何涉及数据库的内容型号).

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.

当用户在其数据输入末尾提交表单时发生的控制器发布操作也应执行与AJAX操作相同的验证,只是为了避免用户之间的竞争状况.

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.

这篇关于将验证逻辑放在MVC软件体系结构中的何处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆