Search code examples
javascriptregexacrobat

Acrobat Form Field RegEx Validation


I have a form field in my PDF that requires five capitalized letters as input, or nothing at all. Everything else should result in an error. I got the first part working, but I'm making some kind of mistake in checking for an empty field. Here's my Javascript:

event.rc = true;
var myRegExp = /^[A-Z]{5}$/;
var myTextInput = event.value;
if ( !myRegExp.test(myTextInput) || myTextInput != "" )
{
    app.alert("Your order number prefix must be formatted as five characters, all caps.");
    event.rc = false;
}


Solution

  • Change the regex to

    var myRegExp = /^([A-Z]{5})?$/;
    

    to allow an empty string match and remove || myTextInput != "" condition that becomes irrelevant.

    A (...)? group is an optional one because ? matches 1 or 0 occurrences of the quantified subpattern.