Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 569
Romper Avatar asked Mar 21 '17 08:03

Romper


People also ask

What is difference between @NotEmpty and @NotBlank?

@NotEmpty: a constrained CharSequence, Collection, Map, or Array is valid as long as it's not null, and its size/length is greater than zero. @NotBlank: a constrained String is valid as long as it's not null, and the trimmed length is greater than zero.

How do you validate a space in Java?

In order to check if a String has only unicode digits or space in Java, we use the isDigit() method and the charAt() method with decision making statements. The isDigit(int codePoint) method determines whether the specific character (Unicode codePoint) is a digit. It returns a boolean value, either true or false.

What does javax validation constraints NotNull do?

@NotNull validates that the annotated property value is not null. @AssertTrue validates that the annotated property value is true. @Size validates that the annotated property value has a size between the attributes min and max; can be applied to String, Collection, Map, and array properties.

What is @NotNull annotation in spring boot?

One way we can protect our code is to add annotations such as @NotNull to our method parameters. By using @NotNull, we indicate that we must never call our method with a null if we want to avoid an exception.


1 Answers

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;
    }
}
like image 177
Ken Bekov Avatar answered Sep 20 '22 04:09

Ken Bekov