9

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

2
  • Are you validating it in Spring MVC app with @Valid annotation? If yes, just annotate in TopDtoForm your list with @Valid and add @NotEmpty to DownDto. Spring will validate it just fine Commented Sep 16, 2014 at 15:05
  • @RequestMapping(value = "/submitForm.htm", method = RequestMethod.POST) public @ResponseBody String saveForm(@Valid @ModelAttribute("topDtoForm") TopDtoForm topDtoForm, BindingResult result) {....} Commented Sep 16, 2014 at 15:12

1 Answer 1

22

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.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.