Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use @NotEmpty constraint to validate an HTTP request body in Spring Boot?

I have a RestController containing an HTTP endpoint to create a new user.

@RestController
public class UserController {
  @PostMapping("/user")
  public CompletableFuture<ResponseEntity<UserResponse>> createUser(
      @Valid @RequestBody UserRequest userRequest) {

    return CompletableFuture.completedFuture(
        ResponseEntity.status(HttpStatus.ACCEPTED).body(userService.createUser(userRequest)));
  }
}

My UserRequest model is as follows:

@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(NON_NULL)
@NoArgsConstructor
public class UserRequest {

  // @NotNull
  @NotEmpty private String name;
}

Now, every time I invoke the POST /user endpoint with a valid payload (e.g., { "name": "John" }), I get the following error:

HV000030: No validator could be found for constraint 'javax.validation.constraints.NotEmpty' validating type 'java.lang.String'. Check configuration for 'name'"

In other words, the exception is thrown regardless of whether the "name" property was empty or not.

However, when I use the @NotNull constraint instead, the exception is only thrown in the absence of the name property or { "name": null }, as expected.

Am I misusing the @NotEmpty constraint?

like image 810
Sagar Baver Avatar asked Nov 24 '25 22:11

Sagar Baver


2 Answers

For validation String's variable, you should use @NotBlank this constraint check null and blank value for String's variable(blank for example "" or " ") or @NotNull if you want to check the only nullable value

@NotEmpty for Collection's type check.

Check this for more information: https://www.baeldung.com/java-bean-validation-not-null-empty-blank

like image 194
Dmitrii B Avatar answered Nov 26 '25 11:11

Dmitrii B


Maven dependencies (in pom.xml) -

<!-- Java bean validation API - Spec -->
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.1.Final</version>
</dependency>
 
<!-- Hibernate validator - Bean validation API Implementation -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.11.Final</version>
</dependency>
 
<!-- Verify validation annotations usage at compile time -->
<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-validator-annotation-processor</artifactId>
  <version>6.0.11.Final</version>
</dependency>

In the user request model-

import javax.validation.constraints.NotEmpty; 

@NotEmpty(message = "Name cannot be empty")
    private String name;
like image 39
harsh tibrewal Avatar answered Nov 26 '25 13:11

harsh tibrewal



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!