Home > Mobile >  How do I carry out custom validation of non-String value with javax's ConstraintValidator?
How do I carry out custom validation of non-String value with javax's ConstraintValidator?

Time:11-29

In attempting to create custom validation with javax I am getting a compilation error, which suggests to me that only String values can be validated in a custom way. Let me explain: If I attempt to provide an implementation of ConstraintValidator, and @Override isValid, giving a String as its first parameter, there are not any complaints from the compiler.

However, if I attempt the same, giving a custom object as a first parameter, I get the following complaint from the compiler: Method does not override method from its superclass

The code:

public class PersonConstraint implements ConstraintValidator<Custom, String> {

    @Override
    public void initialize(Custom constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
    }

    @Override
    public boolean isValid(CustomerResource value, ConstraintValidatorContext context) {
        //some code.
        return false;
    }
}

What gives? or what don't I understand?

CodePudding user response:

Turns out, I needed to stipulate the parameter type earlier, when creating the class. #generics

public class PersonConstraint implements ConstraintValidator<Custom, CustomerResource> {

    @Override
    public void initialize(Custom constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
    }


    @Override
    public boolean isValid(CustomerResource value, ConstraintValidatorContext context) {
        //some code.
        return false;
    }
}
  • Related