MVC 问题:我应该将表单验证规则放在控制器还是模型中? [英] MVC Question: Should I put form validation rules in the controller or model?

查看:23
本文介绍了MVC 问题:我应该将表单验证规则放在控制器还是模型中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一方面,表单验证可以被视为应用程序逻辑的一部分,因此属于模型.

On one hand form validation could be seen as part of the application logic and therefore belonging in the model.

另一方面,它直接处理来自视图的输入并处理显示错误等.从这个角度来看,将其放入控制器更有意义.

On the other hand, it deals directly with the input coming from view and handles displaying errors, etc. From that angle it makes more sense to put it into controllers.

从 MVC 的角度来看,哪种方法是正确的?

Which one is the right approach from the MVC point of view?

P.S 我的表单验证实际上只包括编写一个字段列表、它们的规则,并将其传递给表单验证库,该库返回真/假是否通过验证.

P.S my form validation actually consists only of writing a list of fields, their rules, and passing it on to a form validation library, which returns true/false on whether it passed validation or not.

示例:

$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
//........
if ($this->form_validation->validate())
    // Process data
else
    $this->register_form(); //A controller action that will show a view with errors

应该将其放入控制器或模型中吗?

Should this be put into a controller or model?

推荐答案

验证是模型的问题.只有模型知道您的数据应该是什么样子.你在模型中描述了你的数据字段,所以你应该在同一个地方描述这个字段的验证规则.

Validation is Model's issue. Only model knows how your data should look like. You describe your data fields in model, so you should describe validation rules for this fields in the same place.

这对我来说似乎很明显,但我很乐意听取对手的意见.

It seems to be obvious for me, but I'd gladly listen to opponents.

这篇关于MVC 问题:我应该将表单验证规则放在控制器还是模型中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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