Ich möchte den Springboot @valid verwenden, um ein Feld von HTTP -Anforderungen zu validieren, aber basierend auf einem anderen Feld derselben HTTP -Anforderung.
Ich habe den folgenden Code:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
org.springframework.boot
spring-boot-starter-parent
3.4.1
question
23
23
UTF-8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-validation
org.springframework.boot
spring-boot-maven-plugin
< /code>
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
class FieldValidationApplication {
public static void main(String[] args) {
SpringApplication.run(FieldValidationApplication.class, args);
}
}
< /code>
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
class FieldValidationController {
@PostMapping("/validate")
String question(@Valid @RequestBody SomeRequest someRequest) {
return "please validate the field";
}
}
< /code>
record SomeRequest(int score,
String fieldPositive,
String fieldZeroAndNegative
)
{ }
< /code>
The validation rules are quite simple:
The request payload has a field score.
If the value of the field score is strictly positive, then I need to check the field fieldPositive is a valid string, and also, that fieldZeroAndNegative is null.
For instance:
{
"score": 1,
"fieldPositive": "thisisok"
}
< /code>
But those are not:
{
"score": 1
}
{
"score": 1,
"fieldPositive": ""
}
{
"score": 1,
"fieldPositive": "below fieldZeroAndNegative should be null",
"fieldZeroAndNegative": "not ok"
}
< /code>
Similar rule for the other field (code just below).
This is what I tried, I created custom annotation:
record SomeRequest(int score,
@ValidateThisFieldOnlyIfScoreIsPositive String fieldPositive,
@ValidateThisFieldOnlyIfScoreIsZeroOrNegative String fieldZeroAndNegative
)
{ }
< /code>
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Constraint(validatedBy = ValidateThisFieldOnlyIfScoreIsPositiveValidator.class)
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface ValidateThisFieldOnlyIfScoreIsPositive
{
String message() default "Field is invalid";
Class[] groups() default {};
Class[] groups() default {};
Class
Springboot @valid auf einem Feld basiert auf dem Wert eines anderen Feldes ⇐ Java
-
- Similar Topics
- Replies
- Views
- Last post