Tucka
Tucka

Reputation: 23

Validating @RequestBody boolean attribute (to be true or false)

so I read a lot of Topics but did not find this information in any of them. If by any chance i missed it I would really appreciate if you would guide me to it :) .

I am using SringBoot and got a User model which has a boolean field - active. I am using a boolean because i read that it is a bad practice to use Boolean for 3 state checks.

The problem is that when i send a RequestBody from Postman and if i leave field active empty it defaults it to false. I read about things like @NotNull annotation with @Validation and @Valid check on Body but that is just not an option with boolean.

Main question: Is it possible to do something like (@AssertTrue or @AssertFalse) on a boolean property? and if not, how is it possible to make sure this property is not empty in the RequestBody then (not using Boolean)?

EDIT: I just thought that code might not be necessary for this question as it is quite straight forward, here you go, Controller method:

@PutMapping()
@PreAuthorize("hasRole('ADMIN')")
public ResponseEntity<User> modifyUser(@RequestBody User userBody)
        throws NotFoundException {

User class property:

    @Column(name = "ACTIVE")
private boolean active;

Upvotes: 1

Views: 4046

Answers (2)

Tucka
Tucka

Reputation: 23

So in the final result i still had to use Boolean, so i was then able to add @NotNull annotation to active field. Sadly still was not able to find answer on how to do it with boolean... Thanks for the reply!

Upvotes: 0

Technical 101
Technical 101

Reputation: 158

boolean data type is a binary representation (true/false). Null value is neither true or false.

By default the value of boolean is false. Reference Primitive Data Types

If you want to do some validation based on the user data that is sent you would have to create the data type as wrapper Boolean. It would depend on the scenario of what you would the interpretation to be.

  1. If null will you be calculating some value and setting the field?
  2. Do you want to store the value as null in the database?

But ideally if a field is boolean the value should be either true or false.

Upvotes: 1

Related Questions