Reputation: 83
Should we validate the data fetched from the database while displaying in UI?
I am validating form on client side as well as server side before saving.
But should I validate the data before presenting on UI?
Upvotes: 2
Views: 1034
Reputation: 117124
You should always validate data when it moves between realms that you do not fully control.
For example, you do not control what a user may enter so you must validate their data.
When it comes to a database, if someone else maintains the schema, if data is added using a process you don't control, or if there are new business requirements then you should validate the data before displaying it to the user.
Upvotes: 1
Reputation: 17412
Should we validate the data fetched from the database while displaying in UI?
No, data in your database should already be validated. At each layer moving downstream the data is validated at the UI, the API server, and the database. With the most important level of validation being the database schema, and the UI and API validation layers acting as a way to fail early as to avoid further processing of invalid information.
But what if a hacker corrupted the data in the database?
Databases have ways to ensure the integrity and reliability of the data (schemas, checksums, redundancy, monitoring tools, etc). The UI and API layers do not need to fail early on validated data.
Upvotes: 1
Reputation: 64943
No, you should validate inputs and work hard to make your validation logic reliable. Hence, you'll be able to blindly rely on your outputs.
Some might argue the opposite. For example, let's say I've defined an input and someone inserts some JavaScript snippet there. Would I validate the whole text before setting it to the input when that text comes from the database?. No, I would make impossible to execute JavaScript in my UI layer instead.
There're a lot of cases like the one I've described above, where defensive actions should be prefered over validating data before binding it to the UI...
Create/Update actions should store data that have been previously validated and/or sanitized.
In summary, I find some kind of paranoia and bad habit validating outputs: it might mean that your validation isn't validating after all.
YES, OF COURSE! after all - a hacker might have tampered with your database and stored malicious code in your database table - ALWAYS assume that data is bad - until proven innocent. ALWAYS validate, never assume data or user input is "valid" and harmless
I feel that this has other solutions:
Upvotes: 3