Localizing Validators

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:

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;
    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)


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.
Localizing Validators

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s