spring - Different validation process for JPA saving and form validation with same entity class -
i have user entity class mapped table in database. in class, there password
field like:
@data @entity @table(name = "users", schema = "...") public class userentity { ... @column(name = "password", nullable = false, length = 64) @notnull @size(min = 8, max = 64) private string password; ... }
this class represents user in whole project source codes.
but problem registration process:
- client passes password in registration form
- controller validates user password
@valid
- service encodes password encrypt algorithm.
- service tries save user calling repository's
save()
- then before saving database, validation occurs again
- user saved database
there 2 validation process, form validation , entity validation.
but should have different validation strategies.
i've implemented 2 different validators related constraint annotations.
what simple way make so?
hibernate validation (ri bean validation) allow validation groups
the example below validate fields in car object
userentity user = ... set<constraintviolation<car>> constraintviolations = validator.validate(user);
but, if want validate fields in first step , other fields in second step? here validation groups
enter in action
constraintviolations = validator.validate(user, step1.class); constraintviolations = validator.validate(user, step2.class);
now, userentity
should modified
@column(name = "password", nullable = false, length = 64) @notnull(groups = step1.class) @size(min = 8, max = 64, groups = step2.class) private string password;
so, in first step, password validated not null meanwhile in step 2 validation size's minimum 8 , maximum 64.
Comments
Post a Comment