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

查看:84
本文介绍了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?

我的表单验证实际上只包括写一个字段列表及其规则,并将其传递给一个表单验证库,它返回true / false

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

推荐答案

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

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天全站免登陆