javajsonvalidationhibernate-validatorjsr

Adding @NotNull or Pattern constraints on List<String>


How can we ensure the individual strings inside a list are not null/blank or follow a specific pattern

@NotNull
List<String> emailIds;

I also want to add a pattern

@Pattern("\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b.")

but I can live without it.But I would definitely like to have a constraint which will check if any strings inside a list are null or blank. Also how would the Json schema look like

"ids": {
      "description": "The  ids associated with this.", 
    "type": "array",
        "minItems": 1,
        "items": {
        "type": "string",
         "required" :true }
 }

"required" :true does not seem to do the job

Solution

  • You can create a simple wrapper class for the e-mail String:

    public class EmailAddress {
    
        @Pattern("\b[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}\b.")
        String email;
    
        //getters and setters
    }
    

    Then mark the field @Valid in your existing object:

    @NotNull
    @Valid
    List<EmailAddress> emailIds;
    

    The validator will then validate each object in the list.