JSR-303: Another Cross Field Check Problem

I have a @Money constraint that points to the annotated Double property, well, money. I wrote a ConstraintValidator that checks if the @Money property @Money valid value, which depends on the Currency instance. For example, the US dollar has both dollar and percentage values, while the Japanese yen does not, so while 19.99 is the real value for the US dollar, it is not for the yen. The value of Currency stored in another property of the same bean.

The problem is finding the Currency property of this bean in ConstraintValidator . I thought about making it a class level check, but it would be rather cumbersome and redundant to write at the class level which fields are money, and more importantly, you can only generate one error message, even if there are more than one monetary ownership is wrong.

Any suggestions, even special Hibernate Validator, are welcome.

Thanks!

+4
source share
1 answer

IMO, the simplest solution is to create a separate java class, say Money , which contains both information and the type of money (i.e. currency) and the value of money.

 public class Money { private Currency currency; private Double value; public Currency getCurrency() { return currency; } public void setCurrency(Currency currency) { this.currency = currency; } public Double getValue() { return value; } public void setValue(Double value) { this.value = value; } public boolean isValid() { if(getCurrency() == null || getValue() == null) { return false; } // critical logic goes here // sample code if("JPY".equalsIgnoreCase(currency.getCurrencyCode())) { int intValue = getValue().intValue(); double diff = getValue() - intValue; if(diff > 0) { return false; } } /*double fractionValue = value - (value % (currency.getDefaultFractionDigits() * 10)); if(fractionValue > currency.getDefaultFractionDigits() * 10) { return false; }*/ return true; } } 

After that, create a restriction: @ValidMoney and MoneyValidator .

 public class MoneyValidator implements ConstraintValidator<ValidMoney, Money> { @Override public void initialize(ValidMoney constraintAnnotation) { // TODO Auto-generated method stub } @Override public boolean isValid(Money value, ConstraintValidatorContext context) { return value.isValid(); } } 

Example: -

 public class Bid { @ValidMoney private Money bidAmount; } 
+3
source

Source: https://habr.com/ru/post/1333516/


All Articles