Andrew T :
I am implementing a microservice which has only to validate Transaction from the request body, and if it is valid, send it to the next microservice. I have implemented the Validator, but it does not seem to work
Transaction DTO:
public class Transaction {
private TransactionType transactionType;
private String iban;
private String CNP;
private String name;
private String description;
private Float sum;
...
}
The Validator:
@Component()
public class TransactionValidation implements Validator {
@Override
public boolean supports(Class<?> aClass) {
return Transaction.class.equals(aClass);
}
@Override
public void validate(Object object, Errors errors) {
Transaction transaction = (Transaction) object;
if(!isValidCnp(transaction.getCNP())){
errors.rejectValue("CNP", "CNP validation error");
}
if(!isValidIban(transaction.getIban())){
errors.rejectValue("IBAN", "IBAN validation error");
}
if(isInputStringEmpty(transaction.getName())){
errors.rejectValue("name", "Name validation error");
}
}
...
}
The Controller does nothing but simply returns the transaction it receives:
@PostMapping()
public Transaction validateTransaction(@RequestBody @Valid Transaction transaction){
return transaction;
}
But it does not seem to work, it seems that the app does not use the Validator implemented above. Why? Do I have to register my validator anywhere?
akk202 :
I believe the @Valid annotation works on JSR-303 validation spec with annotations in your DTO. You have 2 options
public class Transaction {
@NonNull
@NotEmpty
@NumericIbanConstriant
private String iban;
}
@Constraint(validatedBy = NumericIbanConstriantValidator.class)
public @interface NumericIbanConstriant {
}
public NumericIbanConstriantValidator implements ConstraintValidator<NumericIbanConstraint, String> {
// validation logic for iban string being numeric perhaps?
}
OR in your controller directly autowire the TransactionValidation and call "validate" passing in Transaction, and Errors object
@PostMapping()
public Transaction validateTransaction(@RequestBody Transaction transaction, Errors errors){
transactionValidation.validate(transaction, errors);
return transaction;
}