Chapter 7. Validation Functions
In this chapter, we look closely at the individual components of Sofa’s validation function. Sofa has the basic set of validation features you’ll want in your apps, so understanding its validation function will give you a good foundation for others you may write in the future.
CouchDB uses the validate_doc_update function to
prevent invalid or unauthorized document updates from proceeding. We use it
in the example application to ensure that blog posts can be authored only by
logged-in users. CouchDB’s validation functions—like map and reduce functions—can’t
have any side effects; they run in isolation of a request. They have the
opportunity to block not only end-user document saves, but also replicated
documents from other CouchDBs.
Document Validation Functions
To ensure that users may save only documents that provide these
fields, we can validate their input
by adding another member to the _design/ document: the
validate_doc_update function. This
is the first time you’ve seen CouchDB’s external process in action.
CouchDB sends functions and documents to a JavaScript interpreter. This
mechanism is what allows us to write our document validation functions in
JavaScript. The validate_doc_update function gets
executed for each document you want to create or update. If the validation
function raises an exception, the update is denied; when it doesn’t, the
updates are accepted.
Document validation is optional. If you don’t create a validation function, no ...