JavaScript – Ensuring Frontend and Backend Validations are Synchronized

javajavascriptsolidvalidation

Like many Javascript-based rich web apps these days, I have some complicated validation rules implemented on the front-end. The same rules are supposedly repeated exactly on the Java backend but I always find small deviations.

As a believer of the DRY principle, I think something should be done to systematically fix this. Ideally both sides should run the same code and use the same rules, but since running JavaScript on the backend is not allowed, I can only hope to reuse some meta-fied validation rules. Fortunately, I found some library on GitHub that can do this for JSR-303 annotation-based validation. However, a lot of rewriting and refactoring is still required.

On the other hand, the number of rules is limited (< 80 in total) and the current code is clear and simple to understand (just a bunch of if statements). Using a validation framework would require all custom validators to be wrapped and hidden behind generated meta-data not immediately visible during development, so loads of additional learning curve.

It seems my goal to improve the code will really just harms maintainability. What's people's experience on this?

Best Answer

You could use some rule-based DSL to specify the validation rules used by both the front and back ends. This though then requires code on both the front and back ends to read and implement those validation rules. This leads to the problems that the validation rule reading and implementing code has to be written twice. This can still lead to inconsistencies, and it adds to the size of your code base, increasing its complexity.

The way to reduce code complexity and the risks of inconsistent rule checking is to offload all validation to the server side. The JavaScript code then uses AJAX calls to request the back end validate the input. The front end knows nothing about the validation rules, it simply gets told whether the input is valid or not.

Related Topic