Skip to main content
Participant
June 22, 2021
Answered

Leading Zeroes in Validation Script of a Specific Length

  • June 22, 2021
  • 1 reply
  • 1667 views

First off, I am a complete beginner at Javascript for Acrobat, but I've been tasked with moving a form into Acrobat from a very old program. Our department needs the field to be formatted with specifically 3 digits, all being numbers, and with leading zeroes. Anything 1 or 2 digits long has to be prepended with zeroes, and anything over 3 digits needs to be rejected. I have adapted two different validation scripts that work for one part or the other, but not both.

 

Validation Script 1: This one allows only 3 digits, but does not prepend leading zeroes

event.rc = (event.value=="" || /^\d{3}$/.test(event.value)); 

 

I've also tried the keystroke script below in conjunction with the validation script above, but it did not seem to add the zeroes as I'd hoped.

if(!event.willCommit)
{// Reject non-numeric input
event.rc = !/[^\d\.\-]/.test(event.change);
}
else
{// Format with leading zeros
event.value = util.printf("%03d",event.value);
}

 

Validation Script 2: This one prepends leading zeroes, but will accept more than 3 digits

(function(){
var max_len = 3;
var val = event.value;
while (val.length < max_len) {val = "0" + val;}
event.value = val; })();

 

My apologies on formatting, I'm new at this and I don't know what the correct format of the script should look like if it's not proper. What do I need to do to make the field accept only 3 digits, and prepend zeroes to any number submitted with less than 3 digits?

 

Thanks for the help!

 

 

 

 

This topic has been closed for replies.
Correct answer try67

You can use this code:

 

if (event.value) {
	if (/^\d{0,3}$/.test(event.value)==false) {
		app.alert("Error! You must enter 3 digits or less.");
		event.rc = false;
	} else event.value = util.printf("%03d", event.value);
}

1 reply

try67
Community Expert
try67Community ExpertCorrect answer
Community Expert
June 22, 2021

You can use this code:

 

if (event.value) {
	if (/^\d{0,3}$/.test(event.value)==false) {
		app.alert("Error! You must enter 3 digits or less.");
		event.rc = false;
	} else event.value = util.printf("%03d", event.value);
}
bebarth
Community Expert
Community Expert
June 23, 2021

This one in custom keystroke script doesn't allow to type more than 3 digits.

if(!event.willCommit) {
	var aTester=event.value.split("");
	aTester.splice(event.selStart, event.selEnd-event.selStart, event.change);
	var testeChaine=aTester.join("");
	var modeleRegEx=/^\d{0,3}$/;
	event.rc=modeleRegEx.test(testeChaine);
} else {
	var modeleRegEx=/^\d{3}$/;
	if (event.value!="") event.value=util.printf("%03d", event.value);
	event.rc=event.value=="" || modeleRegEx.test(event.value);
}