Write your own RedPen Validator in Java

RedPen is extensible

RedPen is a Java based extensible document validation framework. You can implement your own extension (i.e. validation logic) in Java language.

Write your own validator

You can write your own Validator by simply overriding Validator#validate(Sentence). This is a callback method where you can receive each sentence in a document. To report a validation error in a sentence, use Validator#addError(String message, Sentence sentenceWithError).
Make sure that the class name ends with “Validator”, and your custom validation class need to be placed in either cc.redpen.validator, cc.redpen.validator.sentence, or cc.redpen.validator.section package.

Here is a very simple Validator implementation which checks sentence length:

package cc.redpen.validator.sentence;

import cc.redpen.model.Sentence;
import cc.redpen.validator.Validator;

public class NumberOfCharacterValidator 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) {
      // formerly addValidationError(message,sentence)
      addError("Sentence is shorter than "
        + MIN_LENGTH + " characters long.", sentence);
    if (sentence.getContent().length() > MAX_LENGTH) {
      addError("Sentence is longer than " + MAX_LENGTH
        + " characters long.", sentence);

Please also consult these existing validators for your reference.

Enable your custom Validator

Once you package the validator class in jar file format and put it in $REDPEN_HOME/lib, it’s ready to validate.
Make sure that you specify a validator section in your redpen-conf.xml as follows:

<redpen-conf lang="en">
    <validator name="NumberOfCharacter" />

In name attribute, specify the class name without “Validator”. For instance, name=”NumberOfCharacter” loads NumberOfCharacterValidator. There is no need to specify the package name.

Write your own RedPen Validator in Java

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