Showing posts with label validation. Show all posts
Showing posts with label validation. Show all posts

Friday, June 7, 2013

Use @ScriptAssert logic With a Field Error

The new @ScriptAssert validator by Hibernate can be really useful for throwing together a quick validation rule that spans over several bean properties, but one of the short comings is that you can't specify a field level error.

 So here is a solution to that. You'll probably notice it doesn't extend the script assert logic, it duplicates it. That's because you can't inherit from an annotation.

Wednesday, September 26, 2012

SpringMVC JSR 303 Validator: Certain Fields Need to All Be Populated Or All Empty

This validator is useful when you have an object that certain fields are grouped together in a way that they all need to be populated or all empty.

You supply the field names on the validation annotation, which then during validation uses reflection to get the values from the objects to make sure they are all populated or all empty.  If the validation fails, the error message is attached to each field so that each field could display an error message.

The only drawback to this validator is that it will only work with one group of fields.

To the Code:

Wednesday, September 19, 2012

SpringMVC BindingResult Model Key

When SpringMVC has validation errors with a BindingResult it stores those errors in the model map so they can be displayed on the JSP. I keep forgetting what the model map key where it's stored at so here it is.

org.springframework.validation.BindingResult.<parameter name>

FYI, I use this sometimes for testing my controllers with spring-mvc-test to make sure that validation errors are set.

Something like this:


UPDATE:

You can also use the test framework's built in methods to validate if an error exists or doesn't exist.

Friday, September 14, 2012

SpringMVC Validator: @NotEquals for Numbers

Here is a validator I whipped up for any number that is rejected only for the numbers specified in the annotation.  In retrospect maybe a different name would have been more appropriate since not equals seems to insinuate string type of behavior, but I'm over it.