Answer the question
In order to leave comments, you need to log in
How to validate the value in the request body?
I am building a REST service with Spring Boot.
I have a method that saves an object. The object has an activity field with the String type.
The user at post request can enter any value in json'e. I don't need it, I need to make it so that the user can only enter specific values (for example, 'active' and 'inactive') otherwise show the user an error:
"activity should be active or inactive'
How can I do such a validation?
I would also like to do a check on the Date field so that the date is entered in a specific format, and not just a set of letters
Object model:
@Entity
@Table(name = "test")
public class Test {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private LocalDate beginDate;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private LocalDate endDate;
private String activity;
@Repository
public interface TestRepository extends JpaRepository<Test, Integer> {
}
@Service
public class TestService {
@Autowired
private final TestRepository testRepository;
public TestService(TestRepository testRepository) {
this.testRepository = testRepository;
}
public Test saveTest(Test test) {
return testRepository.save(test);
}
}
@RestController
@RequestMapping("/api/v1/")
public class TestController {
@Autowired
private final TestService testService;
public TestController(TestService testService) {
this.testService = testService;
}
//create test
@PostMapping("test")
public Test createTest(@RequestBody Test test) {
return testService.saveTest(test);
}
}
Answer the question
In order to leave comments, you need to log in
Try using enum instead of String in activity field.
In gson (I use them but without spring), for example, you can specify a specific value
@Entity
@Table(name = "test")
public class Test {
public static enum Activity {
@SerializedName("active") ACTIVE,
@SerializedName("inactive") INACTIVE
}
....
private Activity activity = Activity.INACTIVE;
}
if (!"active".equals(test.getActivity()) || !"inactive".equals(test.getActivity())) {
throw new YourCustomException();
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler({YourCustomException.class})
public Object onYourCustomException(YourCustomException e) {
return "activity should be active or inactive";
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question