git clone https://github.com/MosHelper/spring-boot-validation-example.git
in file "build.gradle"
compile('org.springframework.boot:spring-boot-starter-validation')
in any file "Model" or "Entity"
@NotNull
int id;
@Size(min=2)
String name;
@Email(message = "Email not valid.")
String email;
see other annotation
insert @Valid before @RequestBody .
in controller file
@PostMapping("/post")
public Student postStudent(@Valid @RequestBody Student student){
return student;
}
Complete.
Request
{
"id":2,
"name":"s",
"email":"testtest" // <--- not email valid
}
Response Body
{
"timestamp": "2018-06-19T07:56:51.406+0000",
"status": 400,
"error": "Bad Request",
"errors": [
{
"codes": [
"Email.student.email",
"Email.email",
"Email.java.lang.String",
"Email"
],
"arguments": [
{
"codes": [
"student.email",
"email"
],
"arguments": null,
"defaultMessage": "email",
"code": "email"
},
[],
{
"defaultMessage": ".*",
"arguments": null,
"codes": [
".*"
]
}
],
"defaultMessage": "Email not valid.",
"objectName": "student",
"field": "email",
"rejectedValue": "testtest",
"bindingFailure": false,
"code": "Email"
}
],
"message": "Validation failed for object='student'. Error count: 1",
"path": "/post"
}
- DecimalMax
- DecimalMin
- Digits
- Future
- FutureOrPresent
- Max
- Min
- Negative
- NegativeOrZero
- NotBlank
- NotEmpty
- NotNull
- Null
- Past
- PastOrPresent
- Pattern
- Positive
- PositiveOrZero