Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring validation for list of nested class

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

like image 466
αƞjiβ Avatar asked Sep 16 '14 14:09

αƞjiβ


People also ask

What is the use of @validated annotation?

@Validated annotation is a class-level annotation that we can use to tell Spring to validate parameters that are passed into a method of the annotated class. @Valid annotation on method parameters and fields to tell Spring that we want a method parameter or field to be validated.

What does @valid do in Spring?

The @Valid annotation ensures the validation of the whole object. Importantly, it performs the validation of the whole object graph. However, this creates issues for scenarios needing only partial validation. On the other hand, we can use @Validated for group validation, including the above partial validation.


1 Answers

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

like image 140
kamil Avatar answered Sep 24 '22 01:09

kamil