method marked with @AssertTrue is not invoked

java spring validation bean-validation hibernate-validator

789 观看

1回复

11086 作者的声誉

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?

作者: gstackoverflow 的来源 发布者: 2017 年 12 月 27 日

回应 (1)


3

754 作者的声誉

决定

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.

作者: mark_o 发布者: 27.12.2017 06:38
32x32