0% found this document useful (0 votes)
19 views

Spring boot Validation Cheat sheet

Spring Boot Validation is a framework for validating applications using JSR-303 and JSR-380 standards, allowing developers to annotate POJOs with various validation constraints. It includes mandatory dependencies for validation and optional URI validation, as well as support for custom validators and constraint composition. The framework integrates with Spring MVC controllers to validate request parameters and supports injected validators in services for comprehensive validation management.

Uploaded by

suresh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Spring boot Validation Cheat sheet

Spring Boot Validation is a framework for validating applications using JSR-303 and JSR-380 standards, allowing developers to annotate POJOs with various validation constraints. It includes mandatory dependencies for validation and optional URI validation, as well as support for custom validators and constraint composition. The framework integrates with Spring MVC controllers to validate request parameters and supports injected validators in services for comprehensive validation management.

Uploaded by

suresh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Spring Boot Validation Cheat Sheet

What is Spring Boot Validation? Annotated POJO Hibernate


Spring Boot Validation is a sophisticated validation framework for Spring Boot ap- Attributes in POJOs can be marked with validation annotations. Validation groups annotation validates type
plications based on JSR-303 and JSR-380. can be used to add validations for different scenarios
@EAN the property is an EAN13 code. text
Dependencies class Input { @ISBN the property is an ISBN code text
@Min(1) @Max(10) @Length the property has a length between the at- text
Mandatory Spring Boot Validation Starter private int numberBetweenOneAndTen; tributes min and max
@Range the property has a numeric value between number, text
<dependency> @Email(regexp = "^.+@.+$", groups = Create.class) the attributes min and max
<groupId>org.springframework.boot</groupId> private String email; @URL the property is a URL. text
<artifactId>spring-boot-starter-validation</artifactId> }
<version>2.5.1</version>
</dependency> URI Validator
Annotations annotation validates type
Optional URI Validator The validation of parameters and class attributes can be defined using annotations.
The entries in the type column mean: @Localhost the host is localhost or not. uri
<dependency> @NotLocalhost
any any type @Host the host matches the attribute regex. uri
<groupId>de.schegge</groupId>
<artifactId>uri-validator</artifactId> text CharSequence, String, StringBuilder, . . . @Http @Https the schema is HTTP or HTTPS. uri
<version>0.2.2</version> date all standard Java time and date classes @Schema the schema matches the attribute regex. uri
</dependency> uri URI, URL or text
collection Collection, Map or Array Constraint composition
Usage JSR-303, JSR-380 Validators can be easily implemented. You can also compose your own con-
straints from existing constrains. @HttpNotLocalhost ist composed of @Http and
Spring MVC Controller annotation validates type @NotLocalhost.
The parameter validation of controller endpoint methods is integrated. All accord-
ingly annotated parameters are validated. @NotNull the property is not null. any @Retention(RUNTIME)
@NotEmpty the property is not null or empty collection, @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER,
@RestController text TYPE_USE })
public class ExampleController { @NotBlank the property is not null or whitespace. text @Constraint(validatedBy = {})
@AssertTrue the property is true. boolean @Http @NotLocalhost
@PutMapping("/validate/{id}") @AssertFalse the property is false. boolean public @interface HttpNotLocalhost {
Input validate( @Size the property has a size between the at- collection, String message() default "{cheatsheet.message}";
@PathVariable @Positive Long id, tributes min and max text Class<?>[] groups() default {};
@RequestParam("query") @NotEmpty String query, @Min the property is no smaller than the value number Class<? extends Payload>[] payload() default {};
@Valid @RequestBody Input input) { attribute. }
return input; @Max the property is no larger than the value at- number
} tribute.
} @Positive the property value is strictly positive, re- number
@PositiveOrZero spectivly positive including zero.
@Negative the property is strictly negative, respec- number
Injected Validator @NegativeOrZero tivly negative including zero.
A Validator instance can be injected in each service. @Past the property is in the past, respectivly in- date
@PastOrPresent cluding the present.
@Service @Future the property is in the future, respectivly in- date
public class UserAccountService { @FutureOrPresent cluding the present.
@Autowired @Pattern the property matches the attribute regex. text
private final Validator validator; @Email the property is a valid email address. text
@Valid Marks a property, method parameter or any
public boolean checkAccount(UserAccount useraccount) { method return type for validation cascad-
Set<ConstraintViolation<UserAccount>> violations = ing.
validator.validate(useraccount);
if (!violations.isEmpty()) {
throw new ConstraintViolationException(violations); Spring
}
annotation validates type
return true;
https://www.schegge.de
} @Validated Variant of JSR-303’s @Valid annotation, any
} supporting validation groups. © 2021 Jens Kaiser

You might also like