Search code examples
javaspringspring-bootvalidationspring-validator

Is it possible to change value when using ConstraintValidator in Spring Boot?


I have a string field that may contain whitespaces at leading and trailing. I want to trim these whitespaces and return trimmed text using ConstraintValidator. If the text is null, I want to return null.

When looking at the implementation examples as shown on this link, I am not sure how can I create a method that gets string and return string instead of isValid() method. So, how can I implement this approach based on the given scenario?


Solution

  • Use jackson JsonDeserialize annotation to do this.

    Example:

    import com.fasterxml.jackson.core.JsonParser;
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.DeserializationContext;
    import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
    
    import java.io.IOException;
    
    public class TrimWhiteSpace extends StdDeserializer<String> {
    
      private static final long serialVersionUID = -4993230470571124275L;
    
      public TrimWhiteSpace() {
        this(null);
      }
    
      protected TrimWhiteSpace(final Class<?> vc) {
        super(vc);
      }
    
      @Override
      public String deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
        return p.getText() == null ? null : p.getText().trim();
      }
    }
    

    You can use this annotation as below:

    public class Request {
    
        @JsonDeserialize(using = TrimWhiteSpace.class)
        private String name;
    
    }