0

I'm wondering if such a thing is possible. I have a general DTO class called "Device". Device holds ID and IP. I've set a inner regexp validation to verify if the IP is entered correctly.

But now I want to have another validation of type "verify if this IP is not used by another device"(for both update and create cases).

For this I have written a custom Type orientated ConstraintValidator, where I accomplish the task of checking if the is no other device with the given IP.

But from this point I wanted to go further, and to have several checks and several response error messages from one ConstraintValidator, doing random checks on the Device object.

On this point I couldn't find if I could redefine validator's error message. Is this possible?

Draaksward
  • 759
  • 7
  • 32

2 Answers2

3

You can do this using the following function I use for my own API :

public static void setNewErrorMessage(String newErrorMessage, ConstraintValidatorContext context) {

    context.disableDefaultConstraintViolation();
    context.buildConstraintViolationWithTemplate(newErrorMessage)
            .addConstraintViolation();
}

The context object here is passed in the isValid function of any ConstraintValidator implementing class.

This way you'll be able to do something like :

if(hasError1()) {
     setNewErrorMessage(ERROR1_MESSAGE, context);
     return false;
}

if(hasError2()) {
     setNewErrorMessage(ERROR2_MESSAGE, context);
     return false;
}
Louis-wht
  • 535
  • 5
  • 17
  • Was one foot there:) Formed the Constraint, but didn't use the 'addConstraintViolation'. This one did the trick. Thanks. – Draaksward Aug 27 '18 at 11:36
1

You should use the Hibernate Bean Validation API, to build something like the code below.

HibernateValidatorConfiguration configuration = Validation
        .byProvider( HibernateValidator.class )
        .configure();

ConstraintMapping constraintMapping = configuration.createConstraintMapping();

constraintMapping
    .type( Car.class )
        .property( "manufacturer", FIELD )
            .constraint( new NotNullDef() )
        .property( "licensePlate", FIELD )
            .ignoreAnnotations( true )
            .constraint( new NotNullDef() )
            .constraint( new SizeDef().min( 2 ).max( 14 ) )
    .type( RentalCar.class )
        .property( "rentalStation", METHOD )
            .constraint( new NotNullDef() );

Validator validator = configuration.addMapping( constraintMapping )
        .buildValidatorFactory()
        .getValidator();

Take a look at http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-programmatic-api

Andres
  • 10,561
  • 4
  • 45
  • 63