Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent Spring validation on update

I made a custom validation annotation for unique email (When user registers itself, program checks if email is already in database).

Everything works just fine, but when I need to modify user's info and not to create a new one I run into a problem that says "Email is already in use"

Can I somehow turn off only @UniqueEmail validation(I need the others like email pattern and password validation)?

All validation annotations are in the same User bean.

Thank You.

like image 701
JSEvgeny Avatar asked Oct 30 '22 05:10

JSEvgeny


1 Answers

I'm going to assume that you are using javax.validation.

First you need an interface OnUpdate:

javax.validation.groups.Default

public interface OnUpdate extends Default {}

Now you need to set all the annotations that need to only run on UPDATE:

@NotNull(groups = OnUpdate.class)

Now, you have divided your validations into two groups, those in OnUpdate and those in Default. Running Default will include those in OnUpdate as OnUpdate extends Default.

Now, this is where it gets a little tricky - you need to tell the framework which validations to run on each task.

If using JPA you just need to set the following property:

javax.persistence.validation.group.pre-update = com.my.package.OnUpdate
like image 84
Boris the Spider Avatar answered Nov 09 '22 09:11

Boris the Spider