Skip to main content

Custom Restrictions

Custom Restrictions are restrictions that allow you to provide a validator class.

<simpleValueType name="Iban">
<restrictions>
<restriction name="IbanValidation" type="elements::CustomRestriction">
<validators>
<customRestrictionValidator>
<technology name="JDK"/>
<implementation>net.democritus.types.IbanValidator</implementation>
</customRestrictionValidator>
</validators>
</restriction>
</restrictions>
</simpleValueType>

Each CustomRestriction adds one or more validators, each of which are linked to the underlying technology.

Currently, JDK and EJB3 are supported.

  • JDK: The validator will be added to the SharedValidator class and can only access java standard libraries.
  • EJB3: The validator will be added to the ValidatorBean and has access to ejb-related classes.

Validator Class

The validator has to implement net.democritus.common.validation.Validator. This is an interface that requires 2 methods:

  • setTopic(ValidationTopic) is used to pass down information surrounding the field.
  • validate(T,ValidationReport) is called to validate the value of the field.

The validate method can add messages to the ValidationReport to describe issues.

  public void validate(String iban, ValidationReport report) {
if (iban == null || iban.isEmpty()) return;
try {
IbanUtil.validate(iban.replace(" ", ""), IbanFormat.None);
} catch (IbanFormatException | InvalidCheckDigitException | UnsupportedCountryException e) {
ValidationMessage message = topic.message(e.getMessage());
report.addValidationError(message);
}
}

The messages created with the ValidationTopic already contain a translation key and standard message. You can attach additional information by defining properties. If the message contains a placeholder (e.g. ${foo}), this will be replaced with the provided value.

ValidationMessage message = topic.message(e.getMessage())
.property("foo", "bar");
TOPIC

Topics are defined in the Validator classes. They contain a translation key for the control layer, a reference to the field and readable error message for tracing.

  private final ValidationTopic nameStringLength = new ValidationTopic("space::Starship::name", "space.starship.name.stringLength", "This string should have a length shorter than ${maximum}.");

Custom Translation

Custom translations are expanded with a generic error message. But it is possible to provide your own translations by adding options <restriction.translation.{LANG}>:

<restriction name="IbanValidation" type="elements::CustomRestriction">
<validators/>
<options>
<restriction.translation.nl>
De ingevoerde IBAN waarde is niet correct. Gelieve de waarde na te kijken.
</restriction.translation.nl>
<restriction.translation.en>
The entered IBAN number is invalid. Please check the number and try again.
</restriction.translation.en>
</options>
</restriction>