« Play nice everybody | Main | Chandler, and the hardness of software »

Archetypes validation on the basis of the value of more than one field

In the general category of 'you learn something new every day'.... Today I'm back using Plone (it's been a while!). I'm trying to validate a particular field on the basis of the value of another. Specifically I'm trying to validate a postcode depending on the selected country (so use different validators depending on the country the user has chosen).

If you use Archetypes validators it initially appears as if you are passed the entire object as well as the new value (kwargs['instance']), but unfortunately the validator is called 3 times, and the first two calls have the changed value that you're trying to validate, but the unchanged object. What that means is if the user changed the postcode and the country in the same edit the validator would be using the wrong country on the first call, and raise an error.

Some digging around led me to this reference on the plone site which describes how to correctly validate across multiple fields. Instead of registering a validator as usual, define a pre_validation or post_validation method on your object, pull the values that you need from the REQUEST object, perform your validation as required and write any errors to the errors object. It's not quite as elegant as the general validation machinery, but it certainly does the job.

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)