How do you avoid duplication of validation on the

2019-03-25 10:11发布

How do you avoid duplication of validation on the server and client-side? Is there a web programming platform that generates one from the other, so I don't have to keep the two in sync?

8条回答
我命由我不由天
2楼-- · 2019-03-25 10:49

What you can do is have the server-side validation logic being run by web services that your client-side validation can call via AJAX and also when you post back to your server.

查看更多
虎瘦雄心在
3楼-- · 2019-03-25 10:56

As others mentioned, you should keep the duplication, as the client-side validation is to help the application react sooner to help the user, but, the real validation is on the server-side, as you should never trust anything passed in until it has been validated. You will probably do more extensive validation on the server-side, esp if there is a need to check against a data source, for example, is the username unique would be on the server-side, but is the username long enough, or an email address, could be done on the client-side, and server-side.

I tend to put in comments when there is duplication, especially if I am using a regular expression, to make certain that what changes in one is changed in another.

Good unit tests will help to ensure that these two will always remain in sync.

查看更多
别忘想泡老子
4楼-- · 2019-03-25 11:01

There are frameworks that can generate the client-side validation from serverside validation configuration.

Now I don't know what language or frameworks you are using, but maybe this article can be of help: http://www.emadibrahim.com/2008/09/08/client-server-side-validation-in-aspnet-mvc/

He's using Castle Validator Component together with JQuery and adds some glue to generate the clientside validation based on the serverside validation attributes. It's for asp.net mvc.

/Asger

查看更多
来,给爷笑一个
5楼-- · 2019-03-25 11:04

It's best to do validation on the server side in most cases. You have many different options to make this easier such as Ajax or using sticky forms in PHP. I personally tend to do validation on the server side because the user has the option to turn off JavaScript and they can't turn off validation on the server.....

查看更多
时光不老,我们不散
6楼-- · 2019-03-25 11:07

Asp.net Version 1 had validator controls to do what you are asking

http://msdn.microsoft.com/en-us/library/yb52a4x0.aspx

查看更多
在下西门庆
7楼-- · 2019-03-25 11:09

I think the best way is to use a component that offers both. Their code has been tested, and you don't need to maintain it. I have used Peter Blum's controls in the past with great success. Other than that I think you will have to maintain two code bases if you want to offer both. There is a tool called Script# which can help compile C# to Javascript (it does a translation, not a real compilation), but I am not sure how great it would work for this situation.

查看更多
登录 后发表回答