Springboot @Valid на одном поле, на основе значения другого поляJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Springboot @Valid на одном поле, на основе значения другого поля

Сообщение Anonymous »

Я хотел бы использовать Springboot @Valid для проверки поле HTTP -запроса, но на основе другого поля того же HTTP -запроса.
У меня есть следующий код:

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

Подробнее здесь: https://stackoverflow.com/questions/794 ... ther-field
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»