amphibient
amphibient

Reputation: 31212

Convert empty string to null using javax.validation annotations

I have the following variable annotated for data validation:

@Size(min=8, max=16, message="the size of the parameter must be between 8 and 16")
private String param;

However, the param can be null. It is required that it be 8-16 chars long only if it is not null. The problem I face is if the client app (JSON API) supplies an empty string, I want to treat it as though it were not supplied at all, i.e. is null. I was wondering if there is an elegant way to do this using the javax.validation annotations, i.e. convert an empty string to null, as opposed to the plain Java way the way I'm doing it right now:

public void setParameter(String _param) {
    if(_param != null && !_param.trim().isEmpty()){
        this.param = _param;
    } else {
        this.param = null;
    }
}

I would like to have a very simple setter:

public void setParameter(String _param) {
    this.param = _param;
}

and have the is-empty-string boilerplate done by an annotation. Is there a way to do it?

Upvotes: 0

Views: 3039

Answers (1)

Pat B
Pat B

Reputation: 1955

You could can implement your own custom constraint validator.

see here. I've used this many times and works like a charm.

https://docs.jboss.org/hibernate/validator/5.0/reference/en-US/html/validator-customconstraints.html

You would just need to set this condition (if null return "" or vice-versa) in the isValid method.

Upvotes: 1

Related Questions