I have following class to validate:
@Document(collection = "settings")
public class Settings {
@NotEmpty
private String[] allowableExtensions;
...
@AssertTrue(message = "Each extension must be alphanumeric string with length {2,4}")
public boolean assertTrue() {
for (String extension : allowableExtensions) {
if (extension == null || extension.matches("^[a-zA-Z0-9]{2,6}$")) {
return false;
}
}
return true;
}
}
and following controller:
@PostMapping(value = "/settings/update", consumes = "application/json")
public ResponseEntity<?> updateSettings(@RequestBody @Valid Settings settings, BindingResult bindingResult) {
if(bindingResult.hasErrors()){
return ResponseEntity.badRequest().body(bindingResult.getAllErrors().get(0).getDefaultMessage());
}
}
I didn't find expected errors and put breakpoint into assertTrue method but it doesn't invoke.
What do I wrong?
assertTrue
method does not follow JavaBean convention and you are not doing method validation, hence it is never called and you don't get the violation you are expecting. So for example if you change your Setting
class to something like
public class Settings {
@NotEmpty
private String[] allowableExtensions;
@AssertTrue(message = "Each extension must be alphanumeric string with length {2,4}")
public boolean isAssertTrue() {
for ( String extension : allowableExtensions ) {
if ( extension == null || extension.matches( "^[a-zA-Z0-9]{2,6}$" ) ) {
return false;
}
}
return true;
}
}
you should get this Settings#isAssertTrue
method called and result validated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With