Spring validation for list of nested class

αƞjiβ picture αƞjiβ · Sep 16, 2014 · Viewed 7.9k times · Source

I have implemented my validation for list of custom class as mention in this post. For reference here my code looks like

class TopDtoForm {
  @NotEmpty
  private String topVar;
  private List<DownDto> downVarList;
  //getter and setter
}

class DownDto {
  private Long id;
  private String name;
  //getter and setter
}

@Component
public class TopDtoFormValidator implements Validator {
  @Override
  public boolean supports(Class<?> clazz) {
    return TopDtoForm.class.equals(clazz);
  }

  @Override
  public void validate(Object target, Errors errors) {
    TopDtoForm topDtoForm = (TopDtoForm) target;
    for(int index=0; index<topDtoForm.getDownVarList().size(); index++) {
        DownDto downDto = topDtoForm.getDownVarList().get(index);
        if(downDto.getName().isEmpty()) {
            errors.rejectValue("downVarList[" + index + "].name", "name.empty");
        }
    }
  }
}

So even I send empty name binding result has 0 error. I tested with topVar and it is working fine. My question is do I have to do any other configuration to say use this validator?

Thanks

Answer

kamil picture kamil · Sep 16, 2014

In Spring MVC just annotate in TopDtoForm your list with @Valid and add @NotEmpty to DownDto. Spring will validate it just fine:

class TopDtoForm {
  @NotEmpty
  private String topVar;
  @Valid
  private List<DownDto> downVarList;
  //getter and setter
}

class DownDto {
  private Long id;
   @NotEmpty
  private String name;
  //getter and setter
}

Then in RequestMapping just:

@RequestMapping(value = "/submitForm.htm", method = RequestMethod.POST) public @ResponseBody String saveForm(@Valid @ModelAttribute("topDtoForm") TopDtoForm topDtoForm, BindingResult result) {}

Also consider switching from @NotEmpty to @NotBlank as is also checks for white characters (space, tabs etc.)