Issue
In Spring's MVC, if i have a controller and i want to reject any request with queryparam or requestbody that have fields with leading or trailing spaces, what is the best way to do it? Can we use validators?
@PostMapping(value="/add")
public ResponseEntity<User> addUser(@Validated(AddUser.class) @Requestbody User user, BindingResult result) {
...
// Business logic here
// How to check leading and trailing spaces and throw error if present
...
return responseEntity;
}
In the above say User has firstName and lastName as only fields and i want to check both firstName and lastName don't have any leading or trailing spaces and throw error if they do, what's the best way to do so?
Solution
You can build your own custom validator annotation:
@Target({TYPE, FIELD, ANNOTATION_TYPE, TYPE_USE})
@Retention(RUNTIME)
@Constraint(validatedBy = NoSpacesValidator.class)
@Documented
public @interface NoSpaces {
String message() default "Has trailing or leading spaces!";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class NoSpaceValidator implements ConstraintValidator<NoSpace, String> {
@Override
public void initialize(final NoSpace constraintAnnotation) {
// Empty as no initialize is necessary
}
@Override
public boolean isValid(final String content, final ConstraintValidatorContext context) {
return validate(content);
}
private boolean validate(final String content) {
// I suck
if (StringUtils.isBlank(content)) return false;
return content.trim().length.equals(content.length)
}
}
And then you can annotate your properties with @NoSpace
Answered By - Daniel Wosch