Skip to main content
Known Participant
April 4, 2022
Answered

Validate a drop down list with Javascript

  • April 4, 2022
  • 1 reply
  • 3268 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?

Known Participant
April 5, 2022

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).