0
votes

I had used Hibernate validator with Spring, and the model "Admin" I need to check like this:

@NotEmpty
@Size(min = 4, max = 40)
private String password;

when I save "admin" the password is required, and I used "@Valid @ModelAttribute Admin admin". So it will be checked before save.

But when I update the admin, if the user didn't provide the password, we think that he didn't want to change password, so the null value for the password is legal, for this situation, we couldn't use "@Valid @ModelAttribute Admin admin" anymore, because the password property have been annotation with @NotEmpty, so for this situation, our approach is do by ourselves in the code manually, I suppose if is there a better way to solve? and we still want to use the Bean Validation feature.

And also another issue:

@NotEmpty
@Size(min = 2, max = 20)
private String username;

when we save username, we must check the username whether exists or not, that we need to check the DB, and this situation how to solve if we still use the bean validation, defined a
class level annotation?

I hope anyone could help me. Thanks

2
Don't use your domain objects in your web layer. Use specific objects for each usecase ie. CreateAdminCommand with the properties and validations for that useless. And UpdateAdminCommand/UpdateAdminRequest (or whatever you like) with the properties and validations for that usecase. Gives you intend in your domain and you can have a service method handling those different usecases. The only drawback is you need to copy some data around, the advantage is clarity and you protect your domain.M. Deinum
I personally don't like needing to copy data around and having to maintain this extra layer - smells legacy. And for a simple validation rule like empty or when present values must bear certain rules this is too much.bhantol
@RockyHu Are you using Spring ?bhantol
@bhantol yes,I use the SpringRocky Hu
Check my solution...it needs Spring.bhantol

2 Answers

1
votes

You can use groups. For example, your model would be:

@NotEmpty(groups = CreateAdmin.class)
@Size(min = 4, max = 40)
private String password;

The create admin group.

public interface CreateAdmin {
}

In your Spring controllers, use Spring's @Validated instead of @Valid.

Admin creation method:

@Validated(value = CreateAdmin.class) @ModelAttribute Admin admin

And use the default group in the update method:

@Validated @ModelAttribute Admin admin

Now, the @NotEmpty will only apply when an admin is created.

For your second question, you can create a custom constraint, for example, @UniqueUsername, and check the database in the constraint validator's isValid medthod.

0
votes

We have used SpelAssert from jirutka however such edge cases can also be handled using @Pattern