If you are familiar with more than one natural language. It’s good to consider localizing your custom validators in RedPen.
To localize validation error messages, of course you need to avoid hard-coding error messages in your Validator implementation. To achieve that, use addLocalizedError(Sentence sentenceWithError,Object… args) instead of addError(String message, Sentence sentenceWithError) as follows:
NumberOfCharactersLocalizedValidator
package cc.redpen.validator.sentence; import cc.redpen.model.Sentence; import cc.redpen.validator.Validator; public class NumberOfCharactersLocalizedValidator extends Validator { private final int MIN_LENGTH = 100; private final int MAX_LENGTH = 1000; @Override public void validate(Sentence sentence) { if (sentence.getContent().length() < MIN_LENGTH) { // actual error message is in NumberOfCharactersLocalizedValidator.properties addLocalizedError(sentence, MIN_LENGTH); } if (sentence.getContent().length() > MAX_LENGTH) { // You can specify a message key when you have multiple error message variations addLocalizedError("toolong", sentence, MAX_LENGTH); } } }
Then you can place error messages in YourValidatorName[_LANGUAGE].properties:
NumberOfCharactersLocalizedValidator.properties (default messages)
NumberOfCharactersLocalizedValidator=Sentence is shorter than {0} characters long. NumberOfCharactersLocalizedValidator.toolong=Sentence is longer than {0} characters long.
NumberOfCharactersLocalizedValidator_ja.properties (Japanese messages)
NumberOfCharactersLocalizedValidator=文が{0}文字より短いです。 NumberOfCharactersLocalizedValidator.toolong=文が{0}文字より長いです。
Error messages will be rendered by java.text.MessageFormat and you can put place holders in the error message text.
With the above implementation, you’ll get Japanese validation error message from Japanese environment:
$ ./bin/redpen -c conf/redpen-conf-en.xml ~/mytext.txt mytext.txt:1: ValidationError[NumberOfCharacters], 文が100文字より短いです。 at line: Short paragraph.
, and English validation error message from English environment:
$ ./bin/redpen -c conf/redpen-conf-en.xml ~/mytext.txt mytext.txt:1: ValidationError[NumberOfCharacters], Sentence is shorter than 100 characters long. at line: Short paragraph.