Search code examples
formsacrobat

Nesting Math Functions in Javascript


I am working on an Acrobat form that should only accept positive, whole numbers in a field.

It is ideal if the number is simply reformated to suit the criteria. For example, if a user types in "-1.4", it should simply change to "1".

Is it acceptable to use this as the "Validation Script" for the field:

if (event.value) event.value = Math.abs(Math.round(event.value));

It seems to work, but is it ok to nest functions like this in general, or will it lead to issues.


Solution

  • Rather than change the value during the validation event, prevent an invalid value from being entered in the first place. To allow only numbers with no dashes to be entered, add the following to the custom keystroke event.

    event.rc = !(/[a-zA-Z\-]/.test(event.change));
    

    enter image description here

    You may want to modify the regex to prevent other characters as well. I just did the bare minimum. Remember that you'll need to allow for the delete key, return key, and backspace to be permitted so you can't just limit the regex to 0-9 (which would be the obvious thing to do).