Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
51 additions
and
1 deletion.
There are no files selected for viewing
35 changes: 35 additions & 0 deletions
35
validation/src/main/java/hello/itemservice/web/validation/ItemValidator.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
package hello.itemservice.web.validation; | ||
|
||
import hello.itemservice.domain.item.Item; | ||
import org.springframework.stereotype.Component; | ||
import org.springframework.validation.*; | ||
|
||
@Component | ||
public class ItemValidator implements Validator { | ||
|
||
@Override | ||
public boolean supports(Class<?> clazz) { | ||
return Item.class.isAssignableFrom(clazz); | ||
} | ||
|
||
@Override | ||
public void validate(Object target, Errors errors) { | ||
Item item = (Item) target; | ||
|
||
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "itemName", "required"); | ||
|
||
if (item.getPrice() == null || item.getPrice() < 1000 || item.getPrice() > 1000000) { | ||
errors.rejectValue("price", "range", new Object[]{1000, 1000000}, null); | ||
} | ||
if (item.getQuantity() == null || item.getQuantity() > 10000) { | ||
errors.rejectValue("quantity", "max", new Object[]{9999}, null); | ||
} | ||
//특정 필드 예외가 아닌 전체 예외 | ||
if (item.getPrice() != null && item.getQuantity() != null) { | ||
int resultPrice = item.getPrice() * item.getQuantity(); | ||
if (resultPrice < 10000) { | ||
errors.reject("totalPriceMin", new Object[]{10000, resultPrice}, null); | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters