4

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.

Community
  • 1
  • 1
Michael.Lumley
  • 2,345
  • 2
  • 31
  • 53
  • 2
    You have to write it twice, unfortunately. – elclanrs Sep 19 '14 at 00:26
  • Is it considered better practice to write it server-side and use AJAX or is it considered better practice to write it twice? – Michael.Lumley Sep 19 '14 at 00:30
  • 3
    I'd say it is better practice to write it twice. – elclanrs Sep 19 '14 at 00:33
  • 2
    The only real way to do this DRY that I've found is to use node.js (or something similar - using js as the server side language). Of course there's always the regex way which is writing the validation code as regex once and send it the the client in a JSON array and process it server side in PHP. But regex can't do everything in a readable manner. Specifically comparing number ranges etc, while doable, becomes unmaintainable in regex. – slebetman Sep 19 '14 at 00:36

1 Answers1

2

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

jasonscript
  • 6,039
  • 3
  • 28
  • 43