I have an application where I can create and edit groups. Every group has a unique title. When someone tries to create new group, I check whether there is a group with that title and if so validation fails. The problem is when someone tries to edit group and does not change the title, according to my custom validation there is one group with that title (the one someone is currently editing) and my validation fails, thus user can not save the group. So I would like to ask if anyone might have any solution to this problem. Many thanks for any answer!
My group class
public class UserGroupData implements Serializable {
private Long id;
@NotNull(message = "{NotNull.userGroupData.title}")
@Size(max = 20, message = "{Size.userGroupData.title}")
@UserGroupTitle(message = "{Unique.userGroupData.title}")
private String title;
My validator interface
@Documented
@Constraint(validatedBy = UserGroupTitleValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface UserGroupTitle {
String message();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
My validator
public class UserGroupTitleValidator implements ConstraintValidator<UserGroupTitle, String> {
@Autowired
UserGroupRepo userGroupRepo;
@Override
public void initialize(UserGroupTitle paramA) {
}
@Override
public boolean isValid(String UserGroupTitle, ConstraintValidatorContext ctx) {
UserGroup userGroup = userGroupRepo.findOneByTitle(UserGroupTitle);
if(userGroup!=null){
return false;
}
return true;
}
}