I am trying to implement validations in my application for register user API. i have created RegisterRequest.java dto and my controller is having below code, neither bindingresult working nor the validations.
@PostMapping("/register")public ResponseEntity<AuthenticationResponse> register( @RequestBody @Valid RegisterRequest request, BindingResult bindingResult) { request.setRole(Role.USER); if(bindingResult.hasErrors()){ throw new DataValidationException(); } return ResponseEntity.ok(authenticationService.register(request));}
RegisterRequest.java
import javax.validation.constraints.Email;import javax.validation.constraints.NotBlank;import javax.validation.constraints.Size;import com.jobposting.entity.Role;import lombok.AllArgsConstructor;import lombok.Builder;import lombok.Data;import lombok.NoArgsConstructor;@Data@Builder@AllArgsConstructor@NoArgsConstructorpublic class RegisterRequest { @NotBlank(message = "First name is required") private String firstname; private String lastname; @NotBlank(message = "Email is required") @Email(message = "Email should be valid") private String email; @NotBlank(message = "Password is required") @Size(min = 8, message = "Password must be at least 8 characters long") private String password; @Size(min = 10, max = 10, message = "Contact number must be 10 digits long") @NotBlank(message = "Contact is required") private String contact; private boolean whatsappConsent; private Role role;}
i am calling the api with below body
{"firstname":"john","lastname":"doe","email":"","password":"1234","contact":"81808880","whatsappConsent":true}
and getting response which I have handled in service layer, I am expecting my code to not proceed till the service layer.
{"dateTime": "2024-05-25T18:24:01.0826414","message": "User already present in database","details": "uri=/api/v1/auth/register"}