Top Description Methods
org.hibernate.validator.constraintvalidation

public Interface HibernateConstraintValidatorContext

extends ConstraintValidatorContext
Known Direct Subinterfaces
org.hibernate.validator.constraintvalidation.HibernateCrossParameterConstraintValidatorContext
Known Direct Implementers
org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorContextImpl
Imports
jakarta.validation.ConstraintValidatorContext, org.hibernate.validator.HibernateValidatorConfiguration, .Incubating

A custom ConstraintValidatorContext which allows to set additional message parameters for interpolation.
Authors
Hardy Ferentschik, Gunnar Morling, Guillaume Smet

Method Summary

Modifier and TypeMethod and Description
public HibernateConstraintValidatorContext

Returns:

a reference to itself to allow method chaining
addExpressionVariable
(String
the name under which to bind the expression variable, cannot be null
name
,
Object
the value to be bound to the specified name
value
)

Allows to set an additional expression variable which will be available as an EL variable during interpolation.

public HibernateConstraintValidatorContext

Returns:

a reference to itself to allow method chaining
addMessageParameter
(String
the name under which to bind the parameter, cannot be null
name
,
Object
the value to be bound to the specified name
value
)

Allows to set an additional named parameter which can be interpolated in the constraint violation message.

public HibernateConstraintViolationBuilder
buildConstraintViolationWithTemplate(String
new un-interpolated constraint message
messageTemplate
)

Redeclares jakarta.validation.ConstraintValidatorContext.buildConstraintViolationWithTemplate.

Returns a constraint violation builder building a violation report allowing to optionally associate it to a sub path.
public <C> C

Returns:

an instance of the specified type or null if the current constraint validator payload isn't of the given type
getConstraintValidatorPayload
(Class<C>
the type of payload to retrieve
type
)

Returns an instance of the specified type or null if the current constraint validator payload isn't of the given type.

public HibernateConstraintValidatorContext

Returns:

a reference to itself to allow method chaining
withDynamicPayload
(Object
an object representing additional information about the violation
payload
)

Allows to set an object that may further describe the violation.

Inherited from jakarta.validation.ConstraintValidatorContext:
disableDefaultConstraintViolationgetClockProvidergetDefaultConstraintMessageTemplateunwrap

Method Detail

addExpressionVariableback to summary
public HibernateConstraintValidatorContext addExpressionVariable(String name, Object value)

Allows to set an additional expression variable which will be available as an EL variable during interpolation. The variable will be available for interpolation for all constraint violations generated for this constraint. This includes the default one as well as all violations created by the ConstraintViolationBuilder. To create multiple constraint violations with different variable values, this method can be called between successive calls to jakarta.validation.ConstraintValidatorContext.ConstraintViolationBuilder#addConstraintViolation().

For example:

public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
    HibernateConstraintValidatorContext context = constraintValidatorContext.unwrap( HibernateConstraintValidatorContext.class );

    context.addExpressionVariable( "foo", "bar" );
    context.buildConstraintViolationWithTemplate( "${foo}" )
           .addConstraintViolation();

    context.addExpressionVariable( "foo", "snafu" );
    context.buildConstraintViolationWithTemplate( "${foo}" )
           .addConstraintViolation();

    return false;
 }
 

Parameters
name:String

the name under which to bind the expression variable, cannot be null

value:Object

the value to be bound to the specified name

Returns:HibernateConstraintValidatorContext

a reference to itself to allow method chaining

Exceptions
IllegalArgumentException:
in case the provided name is null
addMessageParameterback to summary
public HibernateConstraintValidatorContext addMessageParameter(String name, Object value)

Allows to set an additional named parameter which can be interpolated in the constraint violation message. The variable will be available for interpolation for all constraint violations generated for this constraint. This includes the default one as well as all violations created by the ConstraintViolationBuilder. To create multiple constraint violations with different variable values, this method can be called between successive calls to ConstraintViolationBuilder#addConstraintViolation().

For example:

public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
    HibernateConstraintValidatorContext context = constraintValidatorContext.unwrap( HibernateConstraintValidatorContext.class );

    context.addMessageParameter( "foo", "bar" );
    context.buildConstraintViolationWithTemplate( "{foo}" )
           .addConstraintViolation();

    context.addMessageParameter( "foo", "snafu" );
    context.buildConstraintViolationWithTemplate( "{foo}" )
           .addConstraintViolation();

    return false;
 }
 

Parameters
name:String

the name under which to bind the parameter, cannot be null

value:Object

the value to be bound to the specified name

Returns:HibernateConstraintValidatorContext

a reference to itself to allow method chaining

Exceptions
IllegalArgumentException:
in case the provided name is null
Since
5.4.1
buildConstraintViolationWithTemplateback to summary
public HibernateConstraintViolationBuilder buildConstraintViolationWithTemplate(String messageTemplate)

Redeclares jakarta.validation.ConstraintValidatorContext.buildConstraintViolationWithTemplate.

Doc from jakarta.validation.ConstraintValidatorContext.buildConstraintViolationWithTemplate.

Returns a constraint violation builder building a violation report allowing to optionally associate it to a sub path. The violation message will be interpolated.

To create the ConstraintViolation, one must call either one of the addConstraintViolation() methods available in one of the interfaces of the fluent API. If another method is called after addConstraintViolation() on ConstraintViolationBuilder or any of its associated nested interfaces an IllegalStateException is raised.

If ConstraintValidator#isValid(Object, ConstraintValidatorContext) returns false, a ConstraintViolation object will be built per constraint violation report including the default one (unless disableDefaultConstraintViolation() has been called).

ConstraintViolation objects generated from such a call contain the same contextual information (root bean, path and so on) unless the path has been overridden.

To create a different ConstraintViolation, a new constraint violation builder has to be retrieved from ConstraintValidatorContext Here are a few usage examples:

//assuming the following domain model
public class User {
    public Map<String,Address> getAddresses() { ... }
}

public class Address {
    public String getStreet() { ... }
    public Country getCountry() { ... }
}

public class Country {
    public String getName() { ... }
}

//From a property-level constraint on User.addresses
//Build a constraint violation on the default path - i.e. the "addresses" property
context.buildConstraintViolationWithTemplate( "this detail is wrong" )
            .addConstraintViolation();

//From a class level constraint on Address
//Build a constraint violation on the default path + "street"
//i.e. the street property of Address
context.buildConstraintViolationWithTemplate( "this detail is wrong" )
            .addPropertyNode( "street" )
            .addConstraintViolation();

//From a property-level constraint on  User.addresses
//Build a constraint violation on the default path + the bean stored
//under the "home" key in the map
context.buildConstraintViolationWithTemplate( "Incorrect home address" )
            .addBeanNode()
                .inContainer( Map.class, 1 )
                .inIterable().atKey( "home" )
            .addConstraintViolation();

//From a class level constraint on User
//Build a constraint violation on the default path + addresses["home"].country.name
//i.e. property "country.name" on the object stored under "home" in the map
context.buildConstraintViolationWithTemplate( "this detail is wrong" )
            .addPropertyNode( "addresses" )
            .addPropertyNode( "country" )
                .inContainer( Map.class, 1 )
                .inIterable().atKey( "home" )
            .addPropertyNode( "name" )
            .addConstraintViolation();

//From a class level constraint on User
//Build a constraint violation on the default path + addresses["home"].<map key>
//i.e. a container element constraint violation for the map key
context.buildConstraintViolationWithTemplate( "the map key is invalid" )
            .addPropertyNode( "addresses" )
            .addContainerElementNode( "<map key>", Map.class, 0 )
                .inIterable().atKey( "invalid" )
            .addConstraintViolation();

Cross-parameter constraints on a method can create a node specific to a particular parameter if required. Let's explore a few examples:

//Cross-parameter constraint on method
//createUser(String password, String passwordRepeat)
//Build a constraint violation on the default path + "passwordRepeat"
context.buildConstraintViolationWithTemplate("Passwords do not match")
            .addParameterNode(1)
            .addConstraintViolation();

//Cross-parameter constraint on a method
//mergeAddresses(Map<String,Address> addresses,
//        Map<String,Address> otherAddresses)
//Build a constraint violation on the default path + "otherAddresses["home"]
//i.e. the Address bean hosted in the "home" key of the "otherAddresses" map parameter
context.buildConstraintViolationWithTemplate(
        "Map entry home present in both and does not match")
            .addParameterNode(1)
            .addBeanNode()
                .inContainer( Map.class, 1 )
                .inIterable().atKey("home")
            .addConstraintViolation();

//Cross-parameter constraint on a method
//mergeAddresses(Map<String,Address> addresses,
//        Map<String,Address> otherAddresses)
//Build a constraint violation on the default path + "otherAddresses["home"].city
//i.e. on the "city" property of the Address bean hosted in
//the "home" key of the "otherAddresses" map
context.buildConstraintViolationWithTemplate(
        "Map entry home present in both but city does not match")
            .addParameterNode(1)
            .addPropertyNode("city")
                .inContainer( Map.class, 1 )
                .inIterable().atKey("home")
            .addConstraintViolation();
Parameters
messageTemplate:String

new un-interpolated constraint message

Returns:HibernateConstraintViolationBuilder

returns a constraint violation builder

Annotations
@Override
getConstraintValidatorPayloadback to summary
public <C> C getConstraintValidatorPayload(Class<C> type)

Returns an instance of the specified type or null if the current constraint validator payload isn't of the given type.

Parameters
type:Class<C>

the type of payload to retrieve

Returns:C

an instance of the specified type or null if the current constraint validator payload isn't of the given type

Annotations
@Incubating
Since
6.0.9
See Also
HibernateValidatorConfiguration#constraintValidatorPayload(Object)
withDynamicPayloadback to summary
public HibernateConstraintValidatorContext withDynamicPayload(Object payload)

Allows to set an object that may further describe the violation. The user is responsible himself to ensure that this payload is serializable in case the jakarta.validation.ConstraintViolation has to be serialized.

Parameters
payload:Object

an object representing additional information about the violation

Returns:HibernateConstraintValidatorContext

a reference to itself to allow method chaining

Since
5.3