开发者

How to use @Valid with custom validation?

开发者 https://www.devze.com 2023-04-04 18:33 出处:网络
i am using hibernate validation annotation framework to validate my domain classes and validating my domain object with @Valid annotation as follows:

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.


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.


i used custom javax validator:

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()));
        }

and it worked fine.

0

精彩评论

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