Skip to main content
Known Participant
April 4, 2022
Answered

Validate a drop down list with Javascript

  • April 4, 2022
  • 1 reply
  • 3287 views

I have a PDF form with a few drop down lists and I want to be able to validate that the person filling the form is not putting the default item. What is the javascript validation code I should be using ?

 

For example : One of my drop down list is Location and the user can choose between all of the locations we have. I added an option that is called « Select here » that is the default item in my drop down list. Is there a javascript code that would validate that the user didn't leave the « Select here » item on ?

This topic has been closed for replies.
Correct answer try67

I did a lookup and I'm not quite sure which one would be the « complete » solution. There are so many answers and reply that I can't seem to find the « final » answer with the right code ?


Here you go:

 

function validateRequiredFields(doc) {
	var emptyFields = [];
	for (var i=0; i<doc.numFields; i++) {
		 var f = doc.getField(doc.getNthFieldName(i));
		 if (f!=null && f.type!="button" && f.required && f.valueAsString==f.defaultValue) {
			emptyFields.push(f.name);
		}
	}

	if (emptyFields.length>0) {
		 app.alert("You must fill in the following fields:\n" + emptyFields.join("\n"));
		 return false;
	}
	return true;
}	

 

And then you can call it like this:

 

if (validateRequiredFields(this)) this.mailDoc({cTo: "me@server.com"});

1 reply

try67
Community Expert
Community Expert
April 5, 2022

What should trigger this validation?

try67
Community Expert
Community Expert
April 5, 2022

Also, what should happen if the default value is selected?

HelpMeForm!
Participant
November 19, 2022

Hey! Thanks so much for this! Extremely helpful. I have a question though; when testing the form (distribute to myself, filling out out, and then submitting via the created button-with your script above), I noticed that once opening the distributed form, a purple bar appears at the top of the form that allows the user to "Submit Form" which completely side steps the JavaScript...any solution for this? (Like preventing that bar from appearing, or changing the code of the Submit Form button attached to it?)


Or alternatively, adding to the script to not only email the fully completed pdf when my created button is clicked, but to also email an excel file (or csv) of the form responses? (I suspect this would get rid in the purple bar with the separate submit form button since it can be shared normally instead of through the "distribute" function...?)