Search code examples
java-ee-6bean-validation

validating that a field is unique using Bean Validation (or JSF)


I have an simple object that has a name

public class Foo {

    private String name

}

Each user on the site may have up to 10 Foo's associated with them. Within this context, when a new Foo is created, I would like to validate that there isn't another foo associated with the same user that already exists.

I could Create a custom Bean Validator But annotations require the paramaeters to be defined during compilation. How would I then pass across the names of the existing Foos?

As suggested in various places, I could use EL expressions as an alternative way to pick up the data. This feels like using a sledgehammer to crack a nut. It also brings in a whole bunch of potential issues to consider least of all being ease of testing.

I could do class-wide validation using a boolean field

@AssertTrue(message="Name already exists")
public boolean isNameUnique() {
    return (existingNames.contains(name));
}

But the validation message would not show up next to the name field. It is a cosmetic issue and this can be a backup plan. However, its not ideal.

Which brings me to the question:

Is there a simple way to write a Bean Validator that can check the value against a collection of values at the field level and meet the following restrictions ?

  • Previous values determined at runtime
  • Not using things like EL expressions
  • Field level validation instead of class level.

EDIT in reponse to Hardy:

The Foo class is an entity persisted within a database. They are picked up and used through a DAO interface.

I could loop through the entities but that means plugging the DAO into the validator and not to mention that the I would need to write the same thing again if I have another class that too has this constraint.


Solution

  • It would help to see how you want to use the Foo class. Can you extend your example code? Are they kept in a list of Foo instances. A custom constraint seems to be a good fit. Why do you need to pass any parameters to the constraints. I would just iterate over the foos and check whether the names are unique.