Not able to validate request body in Spring boot with @Valid
Validation would've worked if the Request
class was like;
public class Request {
@Valid
StudentSignUpRequest data;
// other stuff
}
The fact that you have no class type for data
makes it impossible for validation to be applied on it, ignoring the fact that there isn't even a @Valid
annotation on the field. The @Valid
annotation is used to propagate the validation cascade.
But since you cannot modify Request
object, let's continue with another way to handle validation without doing it manually.
Another way is to trigger validation after you get the StudentSignUpRequest
from request
object;
StudentSignUpRequest signUpRequest = request.getData(StudentSignUpRequest.class);
loginRegistrationService.signUpStudent(signUpRequest) // validation will trigger with this call
What you can do is as follows;
@Service
@Validated
public class LoginRegistrationService {
public void signUpStudent(@Valid StudentSignUpRequest signUpRequest) {
// some logic
}
}
with @Validated
annotation, you will activate the validation check for any @Valid
annotated args in public
methods within that class.
Can be used with method level validation, indicating that a specific class is supposed to be validated at the method level (acting as a pointcut for the corresponding validation interceptor)
This can be costly since you'd want to get any constraint violation as soon as possible without doing any costly jobs for an already doomed request.