Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

method marked with @AssertTrue is not invoked

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?

like image 259
gstackoverflow Avatar asked Dec 27 '17 16:12

gstackoverflow


1 Answers

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.

like image 191
mark_o Avatar answered Nov 03 '22 07:11

mark_o