Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

486
Views
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?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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;
    }
}
over 4 years ago · Santiago Trujillo Report

0

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);
}
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!