Writing RedPen extension with JavaScript

Extending RedPen in JavaScript

We introduced the basics of writing custom validators in the last post. For those who are unfamiliar with Java, we introduced JavaScriptValidator in RedPen v1.3. JavaScriptValidator is a special validator loads Validator implementations written in JavaScript.

Enabling JavaScriptValidator

To enable JavaScriptValidator, simply add <validator name=”JavaScript” /> in your redpen-conf.xml as follows:

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

Write your own validator in JavaScript

Here is a JavaScript version of NumberOfCharacterValidator:

var MIN_LENGTH = 100;
var MAX_LENGTH = 1000;

function validateSentence(sentence) {
  if (sentence.getContent().length() < MIN_LENGTH) {
    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);

The code looks pretty much similar with the Java version. But due to the difference in the type system, the callback method “validate(Sentence sentence)” is referred as “validateSentence(sentence)” in the JavaScript version.


Of course, it’s JavaScript and there is no need to compile / package your validator (Actually your JavaScript code will be compiled into Java byte-code by Nashorn, and it runs very fast than you expect). JavaScriptValidator will pick any *.js file located in $REDPEN_HOME/js directory.
You can simply run the redpen command to get your file validated by the js validator.

$ ./bin/redpen -c myredpen-conf.xml 2be-validated.txt
2be-validated.txt:1: ValidationError[JavaScript], [NumberOfCharacter.js] Sentence is shorter than 100 characters long. at line: very short sentence.
Writing RedPen extension with JavaScript

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 )

Connecting to %s