Search code examples
javavalidationjpa-2.0hibernate-validator

Optional multiple same constraints on field using Bean Validation


I am trying to use Hibernate validator to validate POJO before insert into database.

There is a field in the bean which could be either 8 or 10 in length.

I tried to use the built in constraint List to put them together, expecting either one of the criteria passes than the validation would pass.

@Length.List({@Length(min=8, max=8,message="Code is either 8 or 10 characters in length"),@Length(min=10, max=10,message="Code is either 8 or 10 characters in length")})
public String getCode() {
    return this.code;
}

However, the result shows that all criteria in the list has to passes to make it valid. So I would like to know is there anyway to make it a OR checking instead.


Solution

  • I think the way this annotation works is like this:

    @Length(min = 8, max = 10)  
    public String getCode() {
       return code;
    }
    

    In other words 9 will also be accepted as valid, which isn't what you're looking for. I'm not sure if there's a way to do two validations and an OR operation on them in Hibernate annotations.

    It looks like you can use @Pattern validation for this:

    @Pattern(regexp="(.{8}|.{10})", message="Should either be 8 or 10 characters")
    public String getCode() {
       return code;
    }