ActiveJDBC Validations go I18N!
A few days ago I added new functionality to AJ - something that bothered me for some time. This has to do with the validation framework. The original implementation had a rather simplistic approach where you just attached a validation message to a validation declaration like so:
public class Temperature extends Model{
static{
validateRange("temp", 10, 2000).message("Temperature is outside the limit");
}
}
However, this is good for a simple English - only apps, but certainly insufficient for other languages. So, I rolled up my sleeves and extended these features to provide real internationalization based on Java Resource Bundles.
This new feature allows to enter a resource bundle key instead of a phrase like this:
public class Temperature extends Model{
static{
validateRange("temp", 10, 2000).message("temperature.outside.limits");
}
}
All you need to do is to provide localized (.. or localised :)) property files, as usual in Java:
#activejdbc_messages.properties:
temperature.outside.limits = Temperature is outside acceptable limits, while it needs to be between {0} and {1} for user: {2}
and then voilà, you can get your localized message:
String user = "Tom";
Temperature temp = new Temperature();
if(!temp.save()){
String message = temp.errors().get("temp", user);
System.out.println(message);// prints: Temperature is outside acceptable limits, while it needs to be between 10 and 2000 for user: Tom
}
The code above uses default locale (en, US).
As you can see, the first two parameters in the message were filled out by the validator, while the third one was provided on the fly. This function is called "Split Parameters", and was suggested for implementation by Evan Leonard.
If you used a German bundle:
#activejdbc_messages_de_DE.properties:
temperature.outside.limits = Die Temperatur liegt außerhalb akzeptabler Grenzen, während es sein muss zwischen {0} und {1}
... and the way to get this message is to provide a locale to the errors(locale)
method:
Temperature temp = new Temperature();
temp.set("temp", 5000);
if(!temp.save()){
String message = temp.errors(new Locale("de", "DE")).get(temp); //<<<=== provide locale
System.out.println(message);// prints: Die Temperatur liegt außerhalb akzeptabler Grenzen, während es sein muss zwischen 10 und 2000
}
I also ensured that the new implementation is backwards compatible. If it does not find a key in the bundle, it will print the passed in message verbatim.
For more in this, follow to ActiveJDBC Validations
Happy coding!