输入验证在 MVC 应用程序中属于什么位置? [英] Where does input validation belong in an MVC application?

查看:15
本文介绍了输入验证在 MVC 应用程序中属于什么位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从表单接收输入的 MVC 应用程序.
这是一个登录表单,因此唯一需要的验证是检查输入是否为非空.
现在,在我将其传递给模型之前,我会在控制器中对其进行验证.
这是否是最佳实践?是否属于模型?

I have a MVC application that receives an input from a form.
This is a login form so the only validation that is necessary is to check whether the input is non-empty.
Right now before I pass it to the model I validate it in the controller.
Is this a best practice or not? Does it belong to the model?

推荐答案

我不认为官方的最佳实践将验证限制在 MVC 模式的任何单个部分.例如,您的视图可以(并且应该)使用 Javascript 进行一些预先验证.您的控制器还应该提供相同类型的验证,以及更多与业务逻辑相关的验证.该模型还可以提供验证形式,即不允许空值的设置器.

I don't think there's an official best practice limiting validation to any single part of the MVC pattern. For example, your view can (and should) do some up-front validation using Javascript. Your controller should also offer the same types of validation, as well as more business-logic related validation. The model can also offer forms of validation, i.e., setters not allowing null values.

在 joelonsoftware 上有一个有趣的讨论.

There's an interesting discussion of this at joelonsoftware.

这篇关于输入验证在 MVC 应用程序中属于什么位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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