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?
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?
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;
}
}
@Size
restriction, you can remove @NotBlank
. Blank value will not be accepted anyway. –
Flickinger Try using below method, this will take care of whitespaces. And you don't need to configure/code specific code to each field. This will be helpful when you are dealing with more number of fields. StringTrimmerEditor(true) -- it makes it to null, if it has only whitespaces.
StringTrimmerEditor(false) -- it just trims the leading and trailing whitespaces. if it has only whitespaces, just makes it empty string.
in Controller class:
@InitBinder
public void initialBinderForTrimmingSpaces(WebDataBinder webDataBinder) {
StringTrimmerEditor stringTrimEditor = new StringTrimmerEditor(true);
webDataBinder.registerCustomEditor(String.class, stringTrimEditor);
}
So a much simpler suggestion (at least in my eyes), is to create a method that checks if the trimmed length is less than the min (in this case 2) or simply check when assigning the string. It is much easier and less convoluted then creating a custom annotation. If so, set the name to the trimmed string, else do nothing.
ex:
public void setName(String str){
if(str.trim().length() < 2)
str = str.trim();
this.name = str;
}
I myself was thinking this exact question, but while I did not want to have a name that was less than 2 legit characters, I did not wish to trim the actual string if it simply had a space between 2 names (ex first and last name).
And yes, I do know this is about 3 years after the question was asked.
© 2022 - 2024 — McMap. All rights reserved.