MVC中的输入验证在哪里进行? [英] Where does input validation happen in MVC?

查看:43
本文介绍了MVC中的输入验证在哪里进行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,这可能是以前问过的,但是我找不到确切的答案.在MVC模式中应该在哪里进行输入验证?

我想说的是,空字段和基本的常规验证之类的事情应该在控制器中发生,而长度和有效字符(例如用户名/密码等)之类的规则应该在模型层中发生.

但是,这意味着在应用程序中散布这种burdon肯定不是一件好事吗?

对不起,如果这个问题很幼稚,但是我对这种类型的编程还比较陌生,想从一开始就使事情变得正确.

解决方案

验证是模型的工作.

由于模型具有各种属性(字段),因此只有模型才能知道输入的哪种组合才能使该模型有效.不仅是一个字段是否为空白,或者该字段的输入是否匹配某种模式,而且有时这是字段输入的组合,或者该模型与确定有效状态的其他模型之间的关系.

您的模型应该封装此逻辑,以便您可以对其进行询问(您是否有效?"),而又不能使其散布在代码的其他部分.

Ok, this has probably been asked before but i cant find a definative answer. Where in the MVC pattern should validation of input happen?

I would like to say that things like empty fields and basic general validation should happen in the controller and that rules as lengths and valid characters of for example usernames / passwords etc should happen at the model layer.

However, this means spreading this burdon around the application which surely cant be good either?

Sorry if this question is naieve but I am relatively new to this type of programming and want to get things correct from the start.

解决方案

Validation is the job of the model.

As models have various attributes (fields), only the models can know what combination of inputs make that model valid. It's not just about whether a field is blank, or the input of that field matches some pattern, but sometimes this is a combination of field inputs, or the model's relationship to other models that determine the valid state.

Your model should encapsulate this logic so you can interrogate it ("are you valid?") and not have it spread across other parts of your code.

这篇关于MVC中的输入验证在哪里进行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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