JQuery Validate Dropdown list

Richard picture Richard · Sep 17, 2012 · Viewed 123.5k times · Source

I'm using the validation plugin from here. I'm trying force the user to select an option in the drop down list so here's my html for the list:

Select the best option<br/>
<select name="dd1" id="dd1">
<option value="none">None</option>
<option value="o1">option 1</option>
<option value="o2">option 2</option>
<option value="o3">option 3</option>
</select> <br/><br/>​

And here's the the jquery validation stuff:

$("#everything").validate({
    onsubmit: true,
    rules: {
     dd1: {
      required: {
        depends: function(element) {
            return $("#dd1").val() == "none";
        }
      }
    },
    messages: {
     dd1: {
      required: "Please select an option from the list, if none are appropriate please select 'Other'",
     },
    }
});

I don't see any problems but even when the i select none from the drop down list and click submit, it won't validate it and so doesn't show any messages. Can anyone tell me what i'm doing wrong?

Answer

Ethan Brown picture Ethan Brown · Sep 18, 2012

The documentation for required() states:

To force a user to select an option from a select box, provide an empty options like <option value="">Choose...</option>

By having value="none" in your <option> tag, you are preventing the validation call from ever being made. You can also remove your custom validation rule, simplifying your code. Here's a jsFiddle showing it in action:

http://jsfiddle.net/Kn3v5/

If you can't change the value attribute to the empty string, I don't know what to tell you...I couldn't find any way to get it to validate otherwise.