问题
I've read conflicting philosophies on where data validation should happen and it's just confusing me more. Some say it should only be in the database. Others say that the validation rules should be mirrored in other layers like the bll or ui.
Where should the data validation live? Should rules be split across multiple layers? What are some of the actual best practices (as opposed to theory, head in the clouds type stuff) regarding when and where to validate data in an application running on top of a database.
回答1:
My 2 cents:
Data validation should occur in two locations:
The point where data is acted upon, for example validating input parameters to an SQL query.
General validation at the point where data is submitted, for example in a web application some validation should occur on the client. The advantage being that you can quickly notify users of input issues, i.e. incorrectly formed telephone number, string too long etc. However this should not be relied upon to be a authoritative validation check as, in the case of a web application, a malicious user may bypass an client side validation.
In my opinion the database should not be performing general validation, data should be validated/escaped/sanitised before it goes into the database. That said your database schema can give you a level of abstract validation through column data types, constraints etc. That said, any data that could trigger issues with these should be 'cleaned' before it is passed into the database.
This said, there are many wrong ways but there is no right way. Validation depends on the architecture of your application, the nature of the data within in it and how that data is used.
回答2:
it should be done:
- at the point it is first entered
- anywhere along the way it is changed/manipulated
- anywhere along the way it could cause an error or incorrect data
so in a database driven web forms app, for instance, you would have client-side javascript validation, probably some server side validation in the business logic, and then further constraints in the database, ranging from datatype to check constraints.
来源:https://stackoverflow.com/questions/4819678/where-should-data-validation-occur