Swapna Ch
Swapna Ch

Reputation: 105

Setting dynamic data to min and max attributes of @Range annotation - hibernate validators

Iam using Hibernate Validator for validation of data. I have used @Range attribute for validating a particular field.

@Range(min=0,max=100)
private String amount;

This is fine but can i dynamically change the values of min and max instead of hard coding. I mean can i do something like:

@Range(min=${},max=${})
private String amount;

Upvotes: 9

Views: 16772

Answers (2)

prsmax
prsmax

Reputation: 223

If you are using Spring in your project, you can do something like this:

properties file:

min_range = 0
max_range = 100

spring.xml:

<context:component-scan
    base-package="com.test.config" />
<context:annotation-config />

<bean id="appConfigProperties"    class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="location" value="classpath:appconfig.properties" />
</bean>

java:

@Range(min=${min_range},max=${max_range})
private String amount;

It's not dymanic change, but i think you trying to find something like this

Upvotes: 1

Deepak Kumar
Deepak Kumar

Reputation: 1699

Annotations in Java uses constants as parameters. You Cannot change them dynamically.

Compile constants can only be primitives and Strings.Check this link.

IF you want to make it configurable you can declare them as static final.

For Example:

private static final int MIN_RANGE = 1;

private static final int MAX_RANGE = 100;

and then assign in annotation.

@Range(min=MIN_RANGE,max=MAX_RANGE)
private String amount;

The value for annotation attribute must be a constant expression.

Upvotes: 5

Related Questions