Spring validation, how to have PropertyEditor generate specific error message

You’re trying to do validation in a binder. That’s not the binder’s purpose. A binder is supposed to bind request parameters to your backing object, nothing more. A property editor converts Strings to objects and vice versa – it is not designed to do anything else.

In other words, you need to consider separation of concerns – you’re trying to shoehorn functionality into an object that was never meant to do anything more than convert a string into an object and vice versa.

You might consider breaking up your SSN object into multiple, validateable fields that are easily bound (String objects, basic objects like Dates, etc). This way you can use a validator after binding to verify that the SSN is correct, or you can set an error directly. With a property editor, you throw an IllegalArgumentException, Spring converts it to a type mismatch error because that’s what it is – the string doesn’t match the type that is expected. That’s all that it is. A validator, on the other hand, can do this. You can use the spring bind tag to bind to nested fields, as long as the SSN instance is populated – it must be initialized with new() first. For instance:

<spring:bind path="ssn.firstNestedField">...</spring:bind>

If you truly want to persist on this path, however, have your property editor keep a list of errors – if it is to throw an IllegalArgumentException, add it to the list and then throw the IllegalArgumentException (catch and rethrow if needed). Because you can construct your property editor in the same thread as the binding, it will be threadsafe if you simply override the property editor default behavior – you need to find the hook it uses to do binding, and override it – do the same property editor registration you’re doing now (except in the same method, so that you can keep the reference to your editor) and then at the end of the binding, you can register errors by retrieving the list from your editor if you provide a public accessor. Once the list is retrieved you can process it and add your errors accordingly.

Leave a Comment