Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SpringBoot Bean validation @NotEmpy is not Working

I been trying to use spring @NotEmpty to make some input paramters in a REST api mandatory.

So far this is what I've achieved.

RestController

@RestController
public class ResourceController {

    @Autowired
    private GestionaDatosCrmService service;

    @PostMapping(path = Constantes.OBTENER_DATOS_CRM)
    @ResponseStatus(HttpStatus.CREATED)
    public ObtenerDatosCrmResponse obtenerDatosCrm(@RequestHeader HttpHeaders headerRequest,
            @Valid @RequestBody ObtenerDatosCrmRequest request, HttpServletResponse headerResponse) {
        return service.obtenerDatosCrm(headerRequest, request, headerResponse);
    }
}

Request Object

import javax.validation.constraints.NotEmpty;

//import org.hibernate.validator.constraints.NotEmpty;

public class ObtenerDatosCrmRequest {

    @NotEmpty(message = "Please provide a number")
    private String numSN;
    private String callID;

    public String getNumSN() {
        return numSN;
    }

    public void setNumSN(String numSN) {
        this.numSN = numSN;
    }

    public String getCallID() {
        return callID;
    }

    public void setCallID(String callID) {
        this.callID = callID;
    }
}

Note this important detail I'm using javax.validation.constraints.NotEmpty for the @NotEmpty annotation but that doesn't work when I change to org.hibernate.validator.constraints.NotEmpty that is Deprecated the @NotEmpty kicks in and I get a 400 Bad request error when testing.

Im using spring boot 2.2.2.RELEASE, is there some know bug or issue about this?

like image 450
Kevin Valdez Avatar asked Nov 23 '25 02:11

Kevin Valdez


1 Answers

I've had exactly the same issue and the solution that worked for me was to explicitly require a newer hibernate-validator version.

Gradle:

implementation 'org.hibernate.validator:hibernate-validator:6.1.2.Final'

Maven:

<dependency>
  <groupId>org.hibernate.validator</groupId>
  <artifactId>hibernate-validator</artifactId>
  <version>6.1.2.Final</version>
</dependency>
like image 112
fap Avatar answered Nov 24 '25 16:11

fap



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!