客户端验证和服务器端验证哪个更好?

在我们的情况下,我们使用

jQuery和MVC。 JSON数据在视图和控制器之间传递。

我所做的很多验证都是在用户输入数据时进行验证。 例如,我使用按键事件来防止文本框中出现字母,设置一个最大字符数,并在一个范围内设置一个数字。

我想更好的问题应该是,做服务器端验证比客户端验证有什么好处吗?


很棒的回答每个人。我们拥有的网站是密码保护的,用户基数小(<50)。如果他们没有运行JavaScript,我们将发送忍者。但如果我们为每个人设计一个网站,我同意对双方进行验证。


当前回答

JavaScript可以在运行时修改。

我建议在服务器上创建验证结构,并与客户端共享该结构。

你需要在两端单独的验证逻辑,例如:

客户端输入的“必需”属性

字段。长度> 0服务器端。

但是使用相同的验证规范将消除两端镜像验证的一些冗余(和错误)。

其他回答

好吧,我还是可以回答的。

除了Rob和Nathan的回答,我还想补充一点,客户端验证很重要。当你在你的web表单上应用验证时,你必须遵循以下准则:

客户端

必须使用客户端验证,以过滤来自您网站的真实用户的真实请求。 应该使用客户端验证来减少在服务器端处理期间可能发生的错误。 应该使用客户端验证来最小化服务器端往返,从而节省带宽和每个用户的请求。

服务器端

You SHOULD NOT assume the validation successfully done at client side is 100% perfect. No matter even if it serves less than 50 users. You never know which of your user/emplyee turn into an "evil" and do some harmful activity knowing you dont have proper validations in place. Even if its perfect in terms of validating email address, phone numbers or checking some valid inputs it might contain very harmful data. Which needs to be filtered at server-side no matter if its correct or incorrect. If client-side validation is bypassed, your server-side validations comes to rescue you from any potential damage to your server-side processing. In recent times, we have already heard lot of stories of SQL Injections and other sort of techniques that might be applied in order to gain some evil benefits.

Both types of validations play important roles in their respective scope but the most strongest is the server-side. If you receive 10k users at a single point of time then you would definitely end up filtering the number of requests coming to your webserver. If you find there was a single mistake like invalid email address then they post back the form again and ask your user to correct it which will definitely eat your server resources and bandwidth. So better you apply javascript validation. If javascript is disabled then your server side validation will come to rescue and i bet only a few users might have accidentlly disable it since 99.99% of websites use javascript and its already enabled by default in all modern browsers.

您可以进行服务器端验证,并将每个字段的验证结果发送回一个JSON对象,将客户端Javascript保持在最低限度(只显示结果),并且仍然具有用户友好的体验,而无需在客户端和服务器上重复。

必须始终在服务器上进行验证。

在客户端上进行验证对用户来说也很好,但这是完全不安全的。

我发现了一个有趣的链接,它区分了严重的、系统的、随机的错误。

客户端验证非常适合用于防止严重和随机错误。通常是任何输入的最大长度。不要模仿服务器端验证规则;提供你自己粗略的经验验证规则(例如客户端200个字符;在服务器端,由强业务规则指定的特定n字符小于200)。

服务器端验证非常适合用于防止系统错误;它将执行业务规则。

在我参与的一个项目中,验证是通过ajax请求在服务器上完成的。在客户机上,我相应地显示错误消息。

进一步阅读:严重的、系统性的、随机的错误:

https://answers.yahoo.com/question/index?qid=20080918203131AAEt6GO

做服务器端验证而不是客户端验证的好处是客户端验证可以被绕过/操纵:

最终用户可以关闭javascript 数据可以通过一个定制的应用程序直接发送到你的服务器,而这个人甚至不使用你的网站 页面上的Javascript错误(由各种原因引起)可能导致部分(而不是全部)验证运行

简而言之,始终始终验证服务器端,然后将客户端验证视为增强最终用户体验的“额外”。