Search code examples
javahibernate-validator

How to conditionally validate fields with Hibernate validator?


I want to implement login / create account function. I declared a class 'Member' and set fields 'id', 'name', 'password.' I want to use hibernate-validator to validate the fields. Here I have a problem. When you create an account, you need to enter all of the three fields. So I set @NotBlank for all fields. But when you login, you don't input name field. So you always get error message when you try to login. How do I solve this problem?

I have considered adding dummy characters when you login but it is tricky.. Any other solutions?


Solution

  • As mentioned above, condition validation can be obtained by using validation groups.

    Our reference documentation gives you all the details for that: https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#chapter-groups .

    Groups can be a bit tricky, but considering your simple use case, it should be easy to implement.