Я хотел бы использовать 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
Springboot @Valid на одном поле, на основе значения другого поля ⇐ JAVA
Программисты JAVA общаются здесь
-
Anonymous
1738682312
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
Подробнее здесь: [url]https://stackoverflow.com/questions/79412128/springboot-valid-on-one-field-based-on-the-value-of-another-field[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия