如何同步客户端验证和服务器端验证? [英] How to client-side validation and server-side validation in sync?

查看:131
本文介绍了如何同步客户端验证和服务器端验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,在编写Web应用程序时,我们希望在客户端和服务器端都进行验证以提供即时反馈,以确保数据完整性和安全性.但是,客户端浏览器应用程序通常是用JavaScript编写的.服务器端可以用Java,Php,Ruby,Python和许多其他语言编写.当服务器端由诸如node.js之类的东西支持时,在客户端和服务器上重用相同的验证代码确实很容易,但是如果服务器端基于Rails或Django(或您可以命名的任何其他框架) ),确保验证代码保持同步的最佳方法是什么?必须以多种语言重新实现相同的代码似乎有点多余.

解决方案

如果您牢记以下观点,则可以重复某些验证.

让我们将验证分为两部分. A)商业验证,例如如果选中了复选框Y,则字段X中的金额应大于$ 500". B)基本数据验证,例如数据类型检查,空检查等.(我们可能会争论每个验证都是业务验证,但这纯粹是上下文相关的).

类别A:这是您的业务逻辑的一部分,应仅保留在服务器端.

类别B::这种类型的验证可能会被放置在客户端.但是请记住,可以绕过浏览器端验证 一个>.这并不意味着您根本不应该在浏览器端进行验证,而应将这种验证仅视为节省从服务器进行网络往返的奖励.服务器必须重新执行这些验证.

简而言之,验证不应视为跨层可重用代码的单位.它们的目标各不相同,应该允许冗余.

希望这会有所帮助.

Typically when writing a web-app we want to perform validation on both client side to offer immediate feedback and on server-side to ensure data integrity and security. However, client-side browser apps are typically written in JavaScript. Server-side can be written in Java, Php, Ruby, Python and a host of other languages. When server-side is backed by something like node.js, it is really easy to re-use the same validation code on both client and server, but if server-side is based on Rails or Django (or whatever other framework you can name), what's the best way to make sure the validation code are kept on sync? It seems a bit redundant to have to re-implement the same code in multiple languages.

解决方案

If you keep the following persepective in mind, it may seem okay to duplicate certain validations.

Let's break validations into two parts. A) Business Validations e.g. "Amount in Field X should be greater than $500 if if checkbox Y is checked" B) Basic data validations e.g. datatype checks, null checks etc. (We may debate that every validation is business validation but that is purely context specific).

Category A: It is part of your business logic and should be kept only on server side.

Category B: Validations of this type are potential candidates to be placed on the client side. But keep in mind that browser side validation can be bypassed. This does not imply that you should not have validations on browser side at all but such validations should be considered merely a bonus to save network roundtrip from server. Server must re-perform these validations.

In nutshell, validations should not be considered as unit of reusable code across tiers. Their objective varies and should allow redundancy.

Hope this helps.

这篇关于如何同步客户端验证和服务器端验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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