如何将@Valid与自定义验证一起使用?
我正在使用 hibernate 验证注释框架来验证我的域类 并使用 @Valid 注释验证我的域对象,如下所示:
@RequestMapping(method = RequestMethod.POST)
public String post(@Valid @ModelAttribute("person") Person person,BindingResult errors) {...}
我想知道是否要进行自定义验证,例如检查数据库中是否存在电子邮件,
我现在正在做的是在域中拥有一个属性:
@AssertFalse(message = "{email.missmatch}")
private boolean emailExist;
并将其设置为发布方法:
person.setEmailExist(personDao.isEmailExist(person.getEmail()));
上面正在使用自定义休眠验证器类,我必须验证域 我在设置属性后调用验证器,
但现在使用 @Valid,在设置属性之前调用验证器
,那么,在这种情况下是否有使用 @Valid 的解决方案? 否则它不起作用,如果它不起作用,请建议我在这种情况下如何验证我的域类而不是使用@Valid,该使用什么?
提前致谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以编写完整的自己的验证器,因此您不需要使用 tbat 标记属性进行“破解”。 jsr303 Bean Validation - 规范中描述了如何编写这样的自定义验证。谷歌一下,你还会发现很多带有示例的博客。
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.
我使用了自定义 javax 验证器:
并且工作正常。
i used custom javax validator:
and it worked fine.