开发者

Spring MVC validation: minimum one field required. At least one field required

I do a search by criteria with an DTO entity for filter in the front-end of my application:

public class MyFilter implements Serializable {

    private static final long serialVersionUID = 1L;
    private String name;
    @Enumerated(EnumType.STRING)
    private AccessType accessType;
    private List<MyType> userType;
    private List<OfficeLocation> officeLocation;
    private List<Language> languages;
    private String country;

}

and getters and setters.

In my controller:

@RequestMapping
public ModelAndView list(@ModelAttribute("filter") MyFilter myFilter, BindingResult result) {        
    final ModelAndView mav = new ModelAndView("list");
    // validate
    MyFilterValidator.validate(myFilter, result);
    mav.addObject("filter", myFilter);
    if (result.hasErrors()) {
        return mav;
    }
    // ...
    return mav;
}

I want to validate the search form filter by a validator class:

public class MyFilterValidator implements org.springframework.validation.Validator {

@Override
public void validate(Object object, Errors errors) {
    final MyFilter myFilter = (MyFilter) object;

    if (myFilter == null) {
        errors.reject("error.one.field.required");
    } else {
        if (StringUtils.isEmpty(myFilter.getName()) && myFilter.getAccessType() == null
                && myFilter.getUserType() == null && myFilter.getLanguages() == null
                && StringUtils.isEmpty(myFilter.getCountry())
                && myFilter.getOfficeLocation() == null) {
      开发者_开发问答      errors.reject("error.one.field.required");
        }
    }
}

@Override
public boolean supports(Class inClass) {
    return MyFilter.class.equals(inClass);
}

}

I need to validate if one field is filled, minimum one field of my Filter class is filled. How can I do that in a simple way? I need to check each attribute : StringUtils.isEmpty or .size()<=0, ... ? Is it possible to iterate over each property and check if one of them is not null? To know if one field is fill?


If you need this test very often, then it would be worth to implement a small function that inspect some annotated fields of the DAO by reflection.

public DAO {
   public String nevermind;

   @AtLeastOneOfThem
   public String a; 

   @AtLeastOneOfThem
   public String b; 
}

/**
  * Return True if at least on of the fields annotated by @AtLeastOneOfThem
  * is not Empty. 
  * THIS IS PSEUDO CODE!
  */
public static boolean atLeastOneOfThemIsNotEmpty(Object o) {
   for(Field field : getFieldsAnnotatedWith(AtLeastOneOfThem.class, o) {
      if (field.get() != null && !field.get().empty()) {
         return true;
      }
   }
   return false;
}

If this is too much work, then it would be the fastet way to implment the check in the tradtional handwritten way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜