Search code examples
springspring-mvchibernate-validator

How to use @Valid with custom validation?


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.


Solution

  • You can write yor complet own validators, so you do not need the "hack" with tbat marker property. How you can write such an custom validation is descriped in the jsr303 Bean Validation - specification. Google for it, you will also find lot of blogs with examples.