简体   繁体   中英

Spring hibernate type validation with multiple error messages

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?

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM