Almost every application needs validation, and validation frameworks do support developers for so long now that there finally is a JSR for it. Yet one thing I haven't seen so far: a concept for layering validations. So here it comes

If you try to automate validation you'll soon discover that there are different types of validation which I call 'layers'.

Character level: Many input fields can only use a certain subset of characters. If the field asks for a number this subset might be: {'-','1','2','3','4','5','6','7','8','9','0','.'}. If any character not in this set is present in the input, the input can not be valid. Note: of course the legal set of character might vary depending on your requirements. E.g. it might be allowed to use a '+' as a prefix, or scientific notation, thus you would need to allow 'E' or 'e' as well.

Local level:
On this level a single field ist tested with some arbitrary code, as long as the code can be executed without any network communication. "Must be a number" is such an example, another one would be the requirement, that a number must be in a specific range. Many requirments can be implemented as a regular expression, but this is necessary. When this level of validation is passed, the input should be convertable into the target type (e.g. java.lang.Integer)

Form level: This level contains rules that check the consistency across more than a single field. For example to check a credit card number one needs to compute a checksum. But the algorithm to be used, depends on the type of card, so if the checksum doesn't match, the reason might be an error in the credit card number or a wrongly choosen card type.

Global level: On this level the input fields of the form alone aren't sufficient. Instead some kind of network ressource is required. The most typical case would be the check against a unique key but address validation via a webservice would be another candidate.

Note that while some layers may be implemented in a webpage using javascript it is common knowledge (I hope) that you shouldn't rely on it and always validate on the server side as well.

Ok so now that we have layers, what do we do with it? We should use them to decide when to validate and how to react on validation failure:


Also since the validation gets computational more expensive with every level, one should consider validating against one level only when all other levels succeed without a problem. This keeps the computational costs low, and allows to rely in one validation on the results of other validations.  The drawback is that the user might see one validation message, fixes it just to see another one.