I have tried to implement ‘class constraints’ but have hit an issue and would like advice on my implementation.
At present I receive the following text in the highTemp error field on an error condition.
{CustomTemperatureAlarms.temperatureAlarms}
and not the text in the resource bundle message.properties (see below).
I am not sure if I have implemented my ‘class constraint’ correctly to output a field level validation error.
Thanks for any help.
My class is:
Code:
@Entity
@CustomTemperatureAlarms(field="highTemp")
public class TemperatureAlarms extends Reading{
@NotNull
@Min(-30)
@Max(70)
private int highTemp = 50;
@NotNull
@Min(-30)
@Max(70)
private int lowTemp = 10;
public void setHighTemp(int highTemp) {
this.highTemp = highTemp;
}
public int getHighTemp() {
return highTemp;
}
public void setLowTemp(int lowTemp) {
this.lowTemp = lowTemp;
}
public int getLowTemp() {
return lowTemp;
}
}
My annotation interface is:
Code:
@Target(TYPE)
@Retention(RUNTIME)
@Constraint(validatedBy = CustomTemperatureAlarmsValidator.class)
@Documented
public @interface CustomTemperatureAlarms {
String message() default "{CustomTemperatureAlarms.temperatureAlarms}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String field();
}
My validator is:
Code:
public class CustomTemperatureAlarmsValidator implements ConstraintValidator<CustomTemperatureAlarms, TemperatureAlarms> {
private String field;
private String message;
@Override
public void initialize(CustomTemperatureAlarms customTemperatureAlarms) {
field = customTemperatureAlarms.field();
message = customTemperatureAlarms.message();
}
@Override
public boolean isValid(TemperatureAlarms temperatureAlarms, ConstraintValidatorContext context) {
if (temperatureAlarms.getLowTemp() <= temperatureAlarms.getHighTemp())
{
return true;
}
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(message).addNode(field).addConstraintViolation();
return false;
}
}
And my JSP is:
Code:
<spring:message code="text.highTempAlarm"/>
<form:select path="highTemp">
<c:forEach var="range" begin="0" end="100" step="1">
<form:option value="${range-30}" label="${range-30}"></form:option>
</c:forEach>
</form:select>
<form:errors path="highTemp" cssClass="errors"/>
<spring:message code="text.lowTempAlarm"/>
<form:select path="lowTemp">
<c:forEach var="range" begin="0" end="100" step="1">
<form:option value="${range-30}" label="${range-30}"></form:option>
</c:forEach>
</form:select>
<form:errors path="lowTemp" cssClass="errors"/>
My message.properties has:
Code:
CustomTemperatureAlarms.temperatureAlarms=High < Low