method marked with @AssertTrue is not invoked
Asked Answered
J

1

8

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?

Jammiejammin answered 27/12, 2017 at 16:35 Comment(0)
H
17

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.

Hightension answered 27/12, 2017 at 18:38 Comment(1)
Just to add more clarity. Method name did not match JavaBean method naming convention.Vanir

© 2022 - 2024 — McMap. All rights reserved.