user1272433
user1272433

Reputation: 157

Validating drop down menu JavaScript

I'm working on an existing site with a contact form that's using JavaScript to validate the fields. The original developer wrote the JavaScript and it isn't validating one of the fields correctly. the Field is a dropdown list and it has a default value that they don't want to be selectable, so I need it to return an invalid response if the default option is selected to force the user to make a selection.

Any help would be greatly appreciated.

// Check to make sure Area of Interest is Valid
   var areaVal = $("#req_area").val();
   var areaRegexObj = /^\s*[\w\s]*\s*$/;

   if (areaRegexObj.test(areaVal)) {
      isValid = (isValid == false) ? false : true;
   } else {
      $("#req_area").val("Please specify your Area of Interest");
      isValid = false;
   }

Upvotes: 0

Views: 639

Answers (1)

Jules
Jules

Reputation: 91

Try

var areaVal = $("#req_area option:selected").val();

if (!areaRegexObj.test(areaVal))
    $("#req_area").val("Please specify your Area of Interest");

It is a good idea to have server side validation (if not already) so that a user won't disable JS and submit the form anyway.

Upvotes: 1

Related Questions