Atif Sultanuddin
Atif Sultanuddin

Reputation: 69

Spring MVC Bean Validation

I have to implement validations for a web app that uses Spring MVC 3. The problem is that the bean class has methods like getProperty("name") and setProperty("name",valueObj). The validations have to be done on the data that is returned by passing different values to getProperty("name") , for eg: getProperty("age") should be greater than 16 and getProperty("state") should be required.

I would like to know if there is any support for validation this kind of Bean and if not, what can be the work around.

Thanks, Atif

Upvotes: 0

Views: 1314

Answers (2)

Bozho
Bozho

Reputation: 597106

I don't think so. Bean validation is performed on javabeans, i.e. class fields with getters and setters. Even if you can register a custom validator, and make validation work, binding won't work. You would need to also register a custom binder that populates your object. It becomes rather complicated. So stick to the javabeans convention.

Upvotes: 4

Beau Grantham
Beau Grantham

Reputation: 3456

It sounds like you want to a custom validation class which implements org.springframework.validation.Validator.

@Component
public class MyValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {
        return MyBean.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        MyBean myBean = (MyBean) target;

        if (StringUtils.isBlank(myBean.getProperty("state"))) {
            errors.rejectValue("state", "blank");
        }
    }

}

In your controller you would do manual validaton like follows:

@Autowired
private MyValidator myValidator;

@RequestMapping(value = "save", method = RequestMethod.POST)
public String save(@ModelAttribute("myBean") MyBean myBean, BindingResult result) {

    myValidator.validate(myBean, result);
    if (result.hasErrors()) {
        ...
    }

    ...

}

Upvotes: 2

Related Questions