凡验证用户输入的程序? [英] Where to validate user input in a program?

查看:122
本文介绍了凡验证用户输入的程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我要实现的一个小诊所的公司,它允许用户(这是医生)来安排咨询,登录客户病史等,所以,这将可能是标准的3层应用程序:presentation,控制器和数据层(即会连接到数据库)

Let's say I have to implement a program for a small clinic company that allows its users(this is, the doctors) to schedule consults, log clients medical histories, etc. So, this will probably be the standard 3-layer application: Presentation, Controller and a Data Layer (that'll connect to a database).

我看到3种可能性:


  1. 我的第一个想法是把验证code右键领域层英寸但我觉得,那么我可能会忍不住做A类检查,然后基于B相同的检查,使用A,然后使用B C等,这从另一方面为好,因为它很容易单位 - 测试验证逻辑。

  1. My first idea was to put the validating code right in the Domain Layer. But I feel that then I might be tempted to do the checking on class A, then the same check on B that uses A, then on C that uses B, etc. It on the other hand is good as it is easy to unit-test the validation logic.

有思想的第二所学校,会说,以验证用户输入的最佳场所是尽快,即大概在presentation层(或控制器)。这似乎是一个不错的主意,一般。如果在控制器上,它可能会很容易单元测试了。它还允许你切换视图或数据层,仍然有一切权利。

There's a second school of thought that'll say that the best place to validate user input is as soon as possible, i.e., probably on the Presentation Layer (or in the Controller). This seems like a good idea, generally. If on the Controller, it will probably be easy to unit-test, too. It also allows one to switch the Views or the Data Layer and still have everything right.

尽量把最验证逻辑可能对数据库本身。这似乎是一个好主意,因为它强制没有数据破坏数据库。我看到的问题是,如果我想使用不同的数据存储库,我得数据验证逻辑再次为新的。有了这样的逻辑在领域层,例如,就不会有这个问题。

Try to put the most validating logic possible on the database itself. This seems like a good idea, as it enforces that no data corrupts the database. The problem I see is that if I want to use different data repositories, I'll have to data validation logic again for the new one. Having that kind of logic at the Domain Layer, for example, would not have this problem.

你怎么一般处理这个问题?

How do you generally approach this problem?

推荐答案

如您所知,有不止一处验证数据。

As you've noted, there's more than one place to validate data.

有也验证几个层次:


  1. 正确的格式和类型;所有需要的值present(例如,如果需要的出生日期,确保它看起来是Date类型;如果它是一个字符串,请确保它符合预期的格式,如'YYYY-MM-DD)

  2. 等级1加的经营正确性:已完成的交易是对您的业务规则(例如,出生日期必须早于当天至少有十八年)有效

有思想的学校,说你应该考虑所有的人:

There's a school of thought that says you should consider all of them:


  1. 在客户端验证,以确保为用户提供最佳体验。不要让他们等待往返于服务器,找出什么是错的。将一个JavaScript验证的地方,会告诉他们1级效力的时候了。

  2. 再次验证在服务器端,因为你的服务层可能没有在它前面的用户界面。绑定和验证所有值进入你的服务层。

  3. 执行所有2级验证作为服务层的事务的一部分。请确保输入是从商业的角度来看是正确的。

  4. 如果数据库被多个应用程序共享,把业务逻辑转换的约束,存储过程和触发器来保证数据的完整性。

我不认为这应该是非此即彼的决定。

I don't think these should be "either or" decisions.

这篇关于凡验证用户输入的程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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