Validate elements of a String array with Java Bean Validation

前端 未结 3 1927
Happy的楠姐
Happy的楠姐 2020-12-21 00:44

I have a simple class that has one of its properties as a String array. As per this document, using @Valid on an array, collection etc. will recursively validate each elemen

相关标签:
3条回答
  • 2020-12-21 01:35

    By adding the @Valid annotation like you've done, the validation algorithm is applied on each element (validation of the element constraints).

    In your case the String class has no constraints. The @Pattern constraint you've added is applied to the array and not on each element of it. Since @Pattern constraint cannot be applied on a array, you are getting an error message.

    You can create a custom validation constraint for your array (see Hibernate docs for more info) or you can use a wrapper class like @Jordi Castilla mentioned.

    0 讨论(0)
  • 2020-12-21 01:35

    Another thing worth mentioning is the introduction of type annotation in Java 8 which lets you annotate parameterized type

    private List<@MyPattern String> defaultAppAdminRoles;
    

    It's not yet in the bean-validation standard (surely in next version) but already available in hibernate-validator 5.2.1. Blog entry here for further information.

    0 讨论(0)
  • 2020-12-21 01:50

    First... i'm not sure... but @Pattern only accepts regex, right? Correct sintax is not:

    @Pattern("^[_ A-Za-z0-9]+$")   // delete 'regexp='
    

    If this is not the problem you can create a wrapper class with validators in the attributes:

    public class Role {
    
        @Pattern(regexp="^[_ A-Za-z0-9]+$")
        String adminRole;
    
        //getters and setters
    }
    

    Then just need to mark the field @Valid in your existing object:

    @Valid
    Role[] defaultAppAdminRoles;
    
    0 讨论(0)
提交回复
热议问题