0

i am using hibernate validation annotation framework to validate my domain classes and validating my domain object with @Valid annotation as follows:

@RequestMapping(method = RequestMethod.POST)
    public String post(@Valid @ModelAttribute("person") Person person,BindingResult errors) {...}

and i was wondering if i want to make custom validation like checking if email exists in database

what i am doing right now is to have a property in the domain:

@AssertFalse(message = "{email.missmatch}")
private boolean emailExist;

and i set it in the post method:

person.setEmailExist(personDao.isEmailExist(person.getEmail()));

above was working with custom hibernate validator class i had to validate domains and i was calling the validator after setting the property

but now with @Valid, the validator is called before setting the property

so, is there's a solution to use @Valid with this case ? or it won't work, if it will not work please suggest me how to validate my domain class in this case instead of using @Valid, what to use ?

thanks in advance.

4

2 回答 2

0

您可以编写您自己的验证器,因此您不需要带有 tbat 标记属性的“hack”。jsr303 Bean Validation - 规范中描述了如何编写这样的自定义验证。谷歌一下,你还会发现很多带有示例的博客。

于 2011-09-13T21:16:49.340 回答
0

我使用了自定义 javax 验证器:

Validator validator = Validation.buildDefaultValidatorFactory()
                .getValidator();
        Set<ConstraintViolation<Person>> cvs = validator.validate(person);
        for (ConstraintViolation<Person> cv : cvs) {
            String field = cv.getPropertyPath().toString();
            errors.addError(new FieldError("person", field, cv.getMessage()));
        }

它工作得很好。

于 2011-09-14T12:43:36.133 回答