Adding @Size annotation conditionally if variable is set to specific value in Java Spring Boot

Viewed 29

I have a Java Spring Boot application, and I have a class called "CustomClass". Here is the class definition:

public class CustomClass {
    @Size(min = 3)
    private String name;

    private String type;
}

Right now, I have the size of the name variable set to be a minimum of 3 characters in length. Some logic changed, and I only want that @Size(min = 3) annotation to be applied to the name field only if the type is a specific value, let's say Type 1. So it might look like this:

if (type == "Type 1") @Size(min = 3)
private String name;

Is this possible, or do I need to create a separate class to handle these different constraints?

1 Answers

You can create a separate method for this logic validation, for example like this:

public class CustomClass {
    private String name;

    private String type;

    @JsonIgnore
    @AssertTrue(message = "name must be at least 3 characters long if type is Type 1")
    public boolean isNameValid() {
        if ("Type 1".equals(type)) {
            return name != null && name.length() >= 3;
        }
        return true;
    }
}

Validation mechanism will check this for you.

Related