springbean-validationjavax

javax validation size trim whitespace


I need to validate a field in POJO, it must be min length = 2, ignoring leading and trailing whitespaces

class User {
    @NotBlank
    @Size(min = 2)
    private String name;
}

it not works for " A"

How it should be?


Solution

  • At first Spring will use setter-method to set value of property. And for validate value Spring will get it with getter-method. That means, you can trim value in setter-method for prepare it to validation:

    public class User {
        @NotBlank
        @Size(min = 2)
        private String name;
    
        public void setName(String value){
            this.name = value.trim();
        }
    
        public String getName(){
            return this.name;
        }
    }