el_pup_le
el_pup_le

Reputation: 12179

How to validate a REST request when a request's property is different to entity type

I have an @Valid annotation to validate requests

public ResponseEntity<User> register(@Valid @RequestBody User user) {}

My User entity has password Byte[] because user.password is hashed before being stored. The request will need to have a password property as String, how can I validate the request with the @Valid annotation when there is a mismatch between storage type and the incoming request?

Upvotes: 0

Views: 66

Answers (1)

gargkshitiz
gargkshitiz

Reputation: 2168

You could write your own custom validator and use it over the User class's password field. @Valid annotation used in the controller method will then ensure to run your custom validation just after it gets the value. You would see numerous examples when you google for custom validation spring. Quoting some of them here:

  1. http://dolszewski.com/spring/custom-validation-annotation-in-spring/
  2. http://therealdanvega.com/blog/2017/05/01/add-validation-spring-entities
  3. http://www.baeldung.com/spring-mvc-custom-validator

Upvotes: 1

Related Questions