Berkay Yildiz
Berkay Yildiz

Reputation: 605

Spring RequestBody optional validation

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.

Upvotes: 4

Views: 7584

Answers (1)

alexbt
alexbt

Reputation: 17085

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:

Upvotes: 9

Related Questions