Refactor general validation; add comments and tests.