Skip to main content
Known Participant
Apr 4, 2022 5:34 PM UTC
Answered

Validate a drop down list with Javascript

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 is closed to new replies. Start a new post to keep the conversation going.
try67
try67Correct answer
Community Expert
Apr 6, 2022 10:17 PM UTC

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"});

17 replies

try67
Community Expert
Community Expert
Apr 5, 2022 8:11 AM UTC

What should trigger this validation?

Translate
try67
Community Expert
Community Expert
Apr 5, 2022 8:11 AM UTC

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

Translate
Known Participant
Apr 5, 2022 5:08 PM UTC

What should trigger is the selection of any other choices in the list.

 

If the default value is selected it should have an error message saying : Please choose a valid location (for example).

Translate