Idsa Idsa - 6 days ago 6
jQuery Question

jQuery Validate Required Select

I am trying to validate html select element using jQuery Validate plugin. I set "required" rule to true but it always passes validation because zero index is chosed by default. Is there any way to define empty value that is used by required rule?

UPD. Example. Imagine we have the following html control:

<select>
<option value="default">Choose...</option>
<option value="1">1</option>
<option value="2">2</option>
</select>


I want Validation plugin to use "default" value as empty.

JMP JMP
Answer

You can write your own rule!

 // add the rule here
 $.validator.addMethod("valueNotEquals", function(value, element, arg){
  return arg != value;
 }, "Value must not equal arg.");

 // configure your validation
 $("form").validate({
  rules: {
   SelectName: { valueNotEquals: "default" }
  },
  messages: {
   SelectName: { valueNotEquals: "Please select an item!" }
  }  
 });