Menu

Validation on Spring
📰

Validation on Spring

DEV Community: java·Martin Klestil·about 2 hours ago
#71tE84z0
#devtojava#devto#dev#validation#fullscreen
Reading 0:00
15s threshold

Invalid inputs are the root of all evil! Or would you run your coffee maker on rocks?

How to start ?

We need the dependency:

<dependency> <groupId> org.springframework.boot </groupId> <artifactId> spring-boot-starter-validation </artifactId> </dependency>

Enter fullscreen mode

Exit fullscreen mode

When do we validate?

As a rule of thumb for REST APIs: As soon as a controller method accepts a @RequestBody , it must be preceded by a @Valid !

Valid

@Valid (Standard Jakarta Validation): Placed on method parameters (like @RequestBody ) or fields to trigger validation of nested objects.

Validated

It is a Spring-specific annotation. It is used at the class level when you want to validate @PathVariable or @RequestParam directly in the controller (e.g., @Min (1) Long id), or for validation groups.

Which endpoints are we validating?

Post Because the client send use new data.

Put / Patch When updating, the client also sends the modified data in the body.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.