3

I have a REST API controller like following code. If I use @valid annotation, every field of Client's entity are controlled for validation.

@ResponseBody
@RequestMapping(value = API.UPDATE_CLIENT, produces = ResponseType.JSON, method = RequestMethod.POST)
public HashMap update(
        @PathVariable(value = "id")int id,
        @RequestBody Client clientData
) {

    clientLogic.update(id, clientData);

    ....
}

Client's entity consists of about 5 fields (id, name, address, email, phone). When I update this records, I don't send all of 5 fields in RequestBody. I just want to validate coming from RequestBody.

Berkay Yildiz
  • 595
  • 7
  • 23

1 Answers1

9

You could use spring's @Validated instead and use groups. If I understand correctly, some values will be set, other won't. So, the problem is only with Null checks. You'd want to temporarly allow null values.

(1) Create an interface to be used as a group

public interface NullAllowed {}

(2) Assign the checks to the NullAllowed group

@Email(groups = NullAllowed.class) //email allows null, so you are good
private String email;

@NotNull //skip this check - not assigned to NullAllowed.class
@Size(min=1, groups = NullAllowed.class)
private String name;

(3) Use @Validated and specify the group to validate

public HashMap update(
    @PathVariable(value = "id")int id,
    @Validated(NullAllowed.class) @RequestBody Client clientData)

Only the checks marked with NullAllowed.class will be validated.


Check this out:

Community
  • 1
  • 1
alexbt
  • 16,415
  • 6
  • 78
  • 87