简体   繁体   English

JavaScript:客户端与服务器端验证

[英]JavaScript: client-side vs. server-side validation

Which is better to do client side or server side validation?客户端或服务器端验证哪个更好?

In our situation we are using在我们的情况下,我们正在使用

  • jQuery and MVC. jQuery 和 MVC。
  • JSON data to pass between our View and Controller.在我们的视图和控制器之间传递的 JSON 数据。

A lot of the validation I do is validating data as users enter it.我所做的很多验证都是在用户输入数据时验证数据。 For example I use the the keypress event to prevent letters in a text box, set a max number of characters and that a number is with in a range.例如,我使用keypress事件来阻止文本框中的字母,设置最大字符数以及一个数字在一个范围内。

I guess the better question would be, Are there any benefits to doing server side validation over client side?我想更好的问题是,在客户端进行服务器端验证有什么好处吗?


Awesome answers everyone.真棒回答大家。 The website that we have is password protected and for a small user base(<50).我们拥有的网站是受密码保护的,并且用户群很小(<50)。 If they are not running JavaScript we will send ninjas.如果他们没有运行 JavaScript,我们将发送 ninjas。 But if we were designing a site for everyone one I'd agree to do validation on both sides.但是,如果我们要为每个人设计一个网站,我会同意双方都进行验证。

As others have said, you should do both.正如其他人所说,你应该两者都做。 Here's why:原因如下:

Client Side客户端

You want to validate input on the client side first because you can give better feedback to the average user .您希望首先在客户端验证输入,因为您可以为普通用户提供更好的反馈 For example, if they enter an invalid email address and move to the next field, you can show an error message immediately.例如,如果他们输入了无效的电子邮件地址并移至下一个字段,您可以立即显示错误消息。 That way the user can correct every field before they submit the form.这样,用户可以在提交表单之前更正每个字段。

If you only validate on the server, they have to submit the form, get an error message, and try to hunt down the problem.如果您只在服务器上进行验证,他们必须提交表单、收到错误消息并尝试找出问题。

(This pain can be eased by having the server re-render the form with the user's original input filled in, but client-side validation is still faster.) (这种痛苦可以通过让服务器重新渲染表单并填写用户的原始输入来缓解,但客户端验证仍然更快。)

Server Side服务器端

You want to validate on the server side because you can protect against the malicious user , who can easily bypass your JavaScript and submit dangerous input to the server.您希望在服务器端进行验证,因为您可以防范恶意用户,他们可以轻松绕过您的 JavaScript 并向服务器提交危险输入。

It is very dangerous to trust your UI.信任你的 UI 是非常危险的。 Not only can they abuse your UI, but they may not be using your UI at all, or even a browser .他们不仅可以滥用您的 UI,而且他们可能根本不使用您的 UI,甚至是浏览器 What if the user manually edits the URL, or runs their own Javascript, or tweaks their HTTP requests with another tool?如果用户手动编辑 URL,或者运行他们自己的 Javascript,或者使用其他工具调整他们的 HTTP 请求怎么办? What if they send custom HTTP requests from curl or from a script, for example?例如,如果他们从curl或脚本发送自定义 HTTP 请求怎么办?

( This is not theoretical; eg, I worked on a travel search engine that re-submitted the user's search to many partner airlines, bus companies, etc, by sending POST requests as if the user had filled each company's search form, then gathered and sorted all the results. Those companies' form JS was never executed, and it was crucial for us that they provide error messages in the returned HTML. Of course, an API would have been nice, but this was what we had to do. ) 这不是理论上的;例如,我在一个旅行搜索引擎上工作,该引擎通过发送POST请求将用户的搜索重新提交给许多合作航空公司、巴士公司等,就像用户填写了每个公司的搜索表单一样,然后收集并对所有结果进行了排序。那些公司的表单 JS 从未执行过,对我们来说至关重要的是,他们在返回的 HTML 中提供错误消息。当然,API 会很好,但这是我们必须做的。

Not allowing for that is not only naive from a security standpoint, but also non-standard: a client should be allowed to send HTTP by whatever means they wish, and you should respond correctly.不允许这样做不仅从安全角度来看是幼稚的,而且也是不标准的:应该允许客户端以他们希望的任何方式发送 HTTP,并且您应该正确响应。 That includes validation.这包括验证。

Server side validation is also important for compatibility - not all users, even if they're using a browser, will have JavaScript enabled.服务器端验证对于兼容性也很重要 - 并非所有用户,即使他们使用浏览器,都会启用 JavaScript。

Addendum - December 2016附录 - 2016 年 12 月

There are some validations that can't even be properly done in server-side application code, and are utterly impossible in client-side code , because they depend on the current state of the database.有些验证甚至无法在服务器端应用程序代码中正确完成,而在客户端代码中则完全不可能,因为它们取决于数据库的当前状态。 For example, "nobody else has registered that username", or "the blog post you're commenting on still exists", or "no existing reservation overlaps the dates you requested", or "your account balance still has enough to cover that purchase."例如,“没有其他人注册该用户名”,或“您评论的博客文章仍然存在”,或“现有预订没有与您请求的日期重叠”,或“您的帐户余额仍有足够的金额支付该购买。” Only the database can reliably validate data which depends on related data.只有数据库才能可靠地验证依赖于相关数据的数据。 Developers regularly screw this up , but PostgreSQL provides some good solutions .开发人员经常搞砸这个,但PostgreSQL 提供了一些很好的解决方案

Yes, client side validation can be totally bypassed, always.是的,总是可以完全绕过客户端验证。 You need to do both, client side to provide a better user experience, and server side to be sure that the input you get is actually validated and not just supposedly validated by the client.您需要同时做这两件事,客户端以提供更好的用户体验,服务器端以确保您获得的输入实际上是经过验证的,而不仅仅是假设由客户端验证。

"

I am just going to repeat it, because it is quite important:我只是要重复一遍,因为它非常重要:

Always validate on the server始终在服务器上验证

and add JavaScript for user-responsiveness.并添加 JavaScript 以提高用户响应能力。

The benefit of doing server side validation over client side validation is that client side validation can be bypassed/manipulated:与客户端验证相比,进行服务器端验证的好处是可以绕过/操纵客户端验证:

  • The end user could have javascript switched off最终用户可以关闭 javascript
  • The data could be sent directly to your server by someone who's not even using your site, with a custom app designed to do so甚至没有使用您的网站的人可以将数据直接发送到您的服务器,并使用专门设计的自定义应用程序
  • A Javascript error on your page (caused by any number of things) could result in some, but not all, of your validation running您页面上的 Javascript 错误(由多种原因引起)可能会导致您的部分验证运行,但不是全部

In short - always, always validate server-side and then consider client-side validation as an added "extra" to enhance the end user experience.简而言之 - 始终,始终验证服务器端,然后将客户端验证视为增加的“额外”,以增强最终用户体验。

You must always validate on the server.必须始终在服务器上进行验证。

Also having validation on the client is nice for users, but is utterly insecure.在客户端进行验证对用户来说也很好,但完全不安全。

Well, I still find some room to answer.好吧,我仍然找到一些空间来回答。

In addition to answers from Rob and Nathan, I would add that having client-side validations matters.除了 Rob 和 Nathan 的回答之外,我还要补充一点,客户端验证很重要。 When you are applying validations on your webforms you must follow these guidelines:当您在 Web 表单上应用验证时,您必须遵循以下准则:

Client-Side客户端

  1. Must use client-side validations in order to filter genuine requests coming from genuine users at your website.必须使用客户端验证来过滤来自您网站上真实用户的真实请求。
  2. The client-side validation should be used to reduce the errors that might occure during server side processing.应该使用客户端验证来减少服务器端处理期间可能发生的错误。
  3. Client-side validation should be used to minimize the server-side round-trips so that you save bandwidth and the requests per user.应该使用客户端验证来最小化服务器端的往返行程,以便您节省带宽和每个用户的请求。

Server-Side服务器端

  1. You SHOULD NOT assume the validation successfully done at client side is 100% perfect.您不应该假设在客户端成功完成的验证是 100% 完美的。 No matter even if it serves less than 50 users.即使它为少于 50 个用户提供服务。 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.您永远不知道您的哪个用户/员工变成了“邪恶”并在知道您没有适当的验证的情况下进行一些有害的活动。
  2. 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.无论正确还是不正确,都需要在服务器端进行过滤。
  3. 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.最近,我们已经听到了很多关于 SQL 注入和其他类型的技术的故事,这些技术可能会被应用以获取一些邪恶的好处。

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.如果您在一个时间点收到 10k 个用户,那么您肯定会最终过滤到您的网络服务器的请求数量。 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.所以最好你应用javascript验证。 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.如果 javascript 被禁用,那么您的服务器端验证将得到拯救,我敢打赌,只有少数用户可能会意外禁用它,因为 99.99% 的网站使用 javascript,并且它已经在所有现代浏览器中默认启用。

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

Client side should use a basic validation via HTML5 input types and pattern attributes and as these are only used for progressive enhancements for better user experience (Even if they are not supported on < IE9 and safari, but we don't rely on them).客户端应通过HTML5 输入类型模式属性使用基本验证,因为这些仅用于渐进式增强以获得更好的用户体验(即使 < IE9 和 safari 不支持它们,但我们不依赖它们)。 But the main validation should happen on the server side..但是主要的验证应该发生在服务器端..

I will suggest to implement both client and server validation it keeps project more secure......if i have to choose one i will go with server side validation.我建议同时实施客户端和服务器验证,它可以使项目更加安全......如果我必须选择一个,我将使用服务器端验证。

You can find some relevant information here https://web.archive.org/web/20131210085944/http://www.webexpertlabs.com/server-side-form-validation-using-regular-expression/您可以在这里找到一些相关信息https://web.archive.org/web/20131210085944/http://www.webexpertlabs.com/server-side-form-validation-using-regular-expression/

I came across an interesting link that makes a distinction between gross, systematic, random errors.<\/strong>我遇到了一个有趣的链接,它区分了严重的、系统的、随机的错误。<\/strong>

Client-Side validation<\/code> suits perfectly for preventing gross and random errors. Client-Side validation<\/code>非常适合防止严重和随机错误。 Typically a max length for any input.通常是任何输入的最大长度。 Do not mimic the server-side validation rule;不要模仿服务器端的验证规则; provide your own gross, rule of thumb validation rule (ex. 200 characters on client-side; a specific n<\/code> chars less than 200 on server-side dictated by a strong business rule).提供您自己的总的经验法则验证规则(例如,客户端 200 个字符;服务器端的特定n<\/code>字符少于 200 个,由强大的业务规则决定)。

Server-side validation<\/code> suits perfectly for preventing systematic errors; Server-side validation<\/code>非常适合防止系统错误; it will enforce business rules.它将执行业务规则。

In a project I'm involved in, the validation is done on the server through ajax requests.在我参与的一个项目中,验证是通过 ajax 请求在服务器上完成的。 On the client I display error messages accordingly.在客户端上,我相应地显示错误消息。

Further reading: gross, systematic, random errors:进一步阅读:严重的、系统的、随机的错误:

https:\/\/answers.yahoo.com\/question\/index?qid=20080918203131AAEt6GO<\/a> https:\/\/answers.yahoo.com\/question\/index?qid=20080918203131AAEt6GO<\/a>

"

JavaScript can be modified at runtime. JavaScript 可以在运行时修改。

I suggest a pattern of creating a validation structure on the server, and sharing this with the client.我建议在服务器上创建验证结构并与客户端共享它的模式。

You'll need separate validation logic on both ends, ex:您需要在两端使用单独的验证逻辑,例如:

"required" attributes on inputs client-side inputs客户端的"required"属性

field.length > 0 server-side. field.length > 0服务器端。

But using the same validation specification will eliminate some redundancy (and mistakes) of mirroring validation on both ends.但是使用相同的验证规范将消除两端镜像验证的一些冗余(和错误)。

Client side data validation can be useful for a better user experience: for example, I a user who types wrongly his email address, should not wait til his request is processed by a remote server to learn about the typo he did.客户端数据验证对于更好的用户体验很有用:例如,我是一个错误地输入了他的电子邮件地址的用户,不应该等到他的请求被远程服务器处理后才知道他所做的错字。

Nevertheless, as an attacker can bypass client side validation (and may even not use the browser at all), server side validation is required, and must be the real gate to protect your backend from nefarious users.尽管如此,由于攻击者可以绕过客户端验证(甚至可能根本不使用浏览器),因此需要服务器端验证,并且必须是保护后端免受恶意用户攻击的真正大门。

"

If you are doing light validation, it is best to do it on the client.如果你在做光照验证,最好在客户端上做。 It will save the network traffic which will help your server perform better.它将节省网络流量,这将有助于您的服务器更好地执行。 If if it complicated validation that involves pulling data from a database or something, like passwords, then it best to do it on the server where the data can be securely checked.如果它复杂的验证涉及从数据库或其他东西中提取数据,例如密码,那么最好在可以安全检查数据的服务器上进行。

"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM