MVC-在哪里实施表单验证(服务器端)?
时间:2020-03-05 18:42:44 来源:igfitidea点击:
在编码传统的MVC应用程序时,编码服务器端表单验证的最佳实践是什么?代码是属于控制器层还是模型层?又为什么呢?
解决方案
回答
从维基百科:
Model-view-controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application and the business rules used to manipulate the data; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages details involving the communication to the model of user actions such as keystrokes and mouse movements.
因此,模型可以容纳应用程序和业务规则。
回答
我完全同意乔希。但是,我们可以在Controller和Model之间创建一种验证层,以便可以在对数据进行建模之前对数据进行大多数语法验证。
例如,
验证层将验证日期格式,金额格式,必填字段等。
因此,该模型将纯粹专注于业务验证,例如x数量应大于y数量。
回答
到目前为止,我在MVC方面的经验完全来自于Rails。
Rails会在模型中进行100%的验证。
在大多数情况下,这非常有效。我要说的是十分之九,这就是我们所需要的。
但是,在某些区域中,我们从表单提交的内容与模型不正确匹配。可能会有一些其他的过滤/重新排列等。
解决这些情况的最佳方法是创建人造模型对象,该对象基本上像模型对象一样工作,但与表单数据进行一对一映射。这些伪模型对象实际上不保存任何内容,它们只是带有验证的数据的存储桶。
ActiveForm就是这样的一个例子
一旦数据进入这些数据(并且是有效的),通常只需一个简单的步骤即可将其直接传输到实际模型中。
回答
基本语法检查应在控件中,因为它会转换模型的用户输入。该模型需要进行真实数据验证。