Validate PDF Forms Using JavaScript

It’s possible to perform form validation through document-embedded JavaScript in Web Standalone and Electron.

Information

Working with PDF JavaScript is available when using the Web SDK in standalone operational mode.

JavaScript support is enabled by default. To disable it, set PSPDFKit.Options.PDF_JAVASCRIPT to false before loading PSPDFKit:

PSPDFKit.Options.PDF_JAVASCRIPT = false;
PSPDFKit.load(configuration);

Validating Forms

Form field validation consists of ensuring that the value of a form field is always correct.

Form fields and their corresponding widget annotations can be extended with Action Scripts, which can then be used to perform form field validation: Initialize a PSPDFKit.Actions.JavaScriptAction with a script, and associate it with a form field and a particular trigger event, like onInput, which is triggered when something is typed in a form field.

The following example adds a validation script that will prevent the user from entering the letter a in the new form field:

const widget = new PSPDFKit.Annotations.WidgetAnnotation({
  id: PSPDFKit.generateInstantId(),
  pageIndex: 0,
  boundingBox: new PSPDFKit.Geometry.Rect({
    left: 100,
    top: 150,
    width: 80,
    height: 24
  }),
  formFieldName: "MyValidatedFormField",
  additionalActions: {
    onInput: new PSPDFKit.Actions.JavaScriptAction({
      script:
        "if (event.change != 'a') { event.rc = true; } else { event.rc = false; }"
    })
  }
});
const formField = new PSPDFKit.FormFields.TextFormField({
  name: "MyValidatedFormField",
  annotationIds: PSPDFKit.Immutable.List([widget.id])
});
instance.create([widget, formField]);

For more information about PDF actions, read our PDF Actions guide.

You can set regular action scripts in Adobe Acrobat too. Open the Prepare Form tool and double-click on a form field. Click on the Actions tab and choose Run a JavaScript from the Select Action dropdown box.

Acrobat Form Field Actions dialog

Example of How to Create a JavaScript-Enabled PDF Document Using Adobe Acrobat

Supported Triggers

PSPDFKit for Web supports running JavaScript actions from the following triggers.

WidgetAnnotation

FormField

Supported Features

PSPDFKit has basic support for the most common JavaScript API methods and properties, detailed below.

ℹ️ Note: Each of the methods listed below may support only a subset of the features and parameters detailed in the specification. We therefore advise you to test your JavaScript-enabled documents thoroughly. Please contact support if you run into issues or limitations.

App

  • alert, launchURL, viewerVersion

Console

  • println

Doc

  • getField, removeField, mailDoc, getNthFieldName, resetForm, print

  • numFields, pageNum, info, gotoNamedDest

Util

  • printx, printd, printf

Color

  • convert, transparent, black, white, red, green, blue, cyan, magenta, yellow, dark gray, gray, light gray, custom color arrays

Event

  • value, rc, selStart, selEnd, willCommit, target, change, name, type

Field

  • getArray, checkThisBox, isBoxChecked, getItemAt, setItems, clearItems, setItems, insertItemAt, deleteItemAt, setAction, buttonImportIcon

  • name, value, textColor, fillColor, strokeColor, readonly, exportValues, currentValueIndices, multipleSelection, commitOnSelChange, numItems, hidden, editable, type, page, borderStyle, rotation, defaultValue, doNotSpellCheck, userName, alignment, rect, doc, required, display, calcOrderIndex, comb, doNotScroll, richText, multiline, fileSelect, password, charLimit

ℹ️ Note: At the moment, there’s no support for buttonImportIcon in PSPDFKit for Web and Electron.

Various functions for formatting, validation, and calculation are also supported. You can read Adobe’s documentation to learn more about them.

Number Formatting

  • AFNumber_Format, AFNumber_Keystroke, AFMakeNumber

Percent Formatting

  • AFPercent_Format, AFPercent_Keystroke

Date Formatting

  • AFDate_Format, AFDate_FormatEx, AFDate_Keystroke, AFDate_KeystrokeEx, AFTime_Format, AFTime_FormatEx, AFTime_Keystroke

Special Formatting

  • AFSpecial_Format, AFSpecial_Keystroke, AFSpecial_KeystrokeEx

Simple Formatting

  • AFSimple, AFSimple_Calculate

Range Validation

  • AFRange_Validate

Debugging

If there’s a problem with the JavaScript in a document, it’s a good idea to first check that the scripts don’t contain syntax or logic errors. To see all JavaScript code used in a document:

  • Open Adobe Acrobat.

  • Click Tools.

  • Select Prepare Form.

  • Click the small down arrow on the sidebar.

  • Choose All JavaScripts.

The screenshots below show how the All JavaScripts window appears in Adobe Acrobat.

Acrobat All JavaScripts window
Acrobat JavaScripts editor

JavaScript Logs

If JavaScript is enabled, PSPDFKit will log errors to the console if there’s a problem with the JavaScript code. We tried to make diagnostics as specific as possible to help you debug your documents more easily. For example, the following error message is logged if the script creator mistakenly writes this.getField(4);:

Catalog[58188:7996163] [JavaScript] [Error] Error: Argument name 'cName' has wrong type. Argument has type number, but expected string.

As you can read in the API documentation, getField’s cName argument must be a string.

In this other example, the script contains one API property that we currently don’t support:

Catalog[58188:7996163] [JavaScript] [Error] TypeError: undefined not callable (property 'notSupportedAPI' of [object global])

Learn More

The PDF specification includes JavaScript support based on JavaScript version 1.5 of ISO-16262 (formerly known as ECMAScript). For more information, refer to the following: