Java – Form validation code shared in the frontend and backend API

javajavascriptnode.jsreacttypescript

I have a legacy Java monolithic web application. My goal is to use React on the frontend, keep Java on the backend and add an API for the frontend to use.

My question is how can I write the data validation just once, using it on both the frontend for form validation and on the backend for data validation?

With the API written in java and the data validation written in javascript, is a workable solution to have an intermediate validation proxy API written in javascript+nodejs which then passes validated requests to the java API?

React(js validation) -> nodejs-API(js validation) -> Java-API(no data validation)

Best Answer

Two points:

  1. Validation in the UI is designed to illicit corrections from the user.
    • Human readable explanations
    • UI alert indicators
    • dynamic checking
  2. Validation in the backend is designed to prevent nasty security issues.
    • pass/fail
    • fail fast
    • single pass

While they both do "validate" the document:

  • their intentions are quite different: online vs. offline, full vs. fail fast, verbose vs pass/fail.
  • the resources available are different: Gigabytes vs. MegaBytes, Multiple threads vs. One thread
  • and the sheering forces acting on the code is different: Browser Architectures vs. Server Architectures, the frameworks, and languages, etc...

Just to get this to work, as you've just pointed out, you would need to:

  • reorganise your network architecture,
  • adopt a new platform,
  • ensure you validation library is poly-fillable for both browser and server usage.

That is a high price to pay for de-duplicating just 2000 lines of code.

Related Topic