DRY when validating calculations made client side (Javascript) on the server (PHP)

十年热恋 提交于 2020-01-03 17:24:11

问题


I'm looking to DRY when I am validating a calculation made by the client (javascript) back on the server (PHP). I'm validating on the server to prevent a malicious user from duping the javascript, but I am calculating on the client to avoid the delay and server strain in AJAXing back to the server for the validation.

My question: is there any way to do this DRY, or do I have to write the code out in both languages? If it has to be written out, is it better to AJAX back to the server for DRY purposes, or should I write out the same validation code in both languages?

This question is exactly what I am looking for an answer to, but it was never satisfactorily answered.

EDIT (1/25/15): Although the accepted answer stands, particularly because my original question specified that the server was running on PHP, I think its worth pointing out that server side validation could be done using Node.js, which allows javascript code to run on the backend server. I have subsequently moved to this approach, and it does allow for reuse of code on both the client and the server, which would allow the kind of write once validation described above. In retrospect @slebetman's comment below identified the best approach for me.


回答1:


Client-side validation is all about saving the user time. By not having to send bad data to the server and then having the request rejected, we can save loading time.

Server-side validation is about security. We need to make sure that the data we get on the server is valid and not going to cause us any problems.

So in my opinion, it's best to write the code twice and not to use AJAX requests to validate data unless you have to



来源:https://stackoverflow.com/questions/25924499/dry-when-validating-calculations-made-client-side-javascript-on-the-server-ph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!