I have a html select with a default value -1.
<select id="BusinessDistrictId">
<option value="-1">Select one...</option>
//other options...
</select>
I would like to force the users to select any option other than -1 value. My jquery validation rules-
rules: {
BusinessDistrictId: { required: true , min:0}
}
But it's not working. Any suggestion?
If you want to validate this element with the jQuery Validate plugin, there are two problems with its markup...
<select id="BusinessDistrictId">
<option value="-1">Select one...</option>
//other options...
</select>
1) As per the requirements of the jQuery Validate plugin, every element must have a unique name
attribute. When rules are declared within .validate()
, they are identified by their name
. However, no matter how rules are declared, every element must still have a unique name
attribute because that's how the plugin keeps track of the form elements.
2) Your min: 0
rule is only a workaround for a broken required
rule. In order to use required: true
on a <select>
element, you must have the value=""
attribute on the first <option>
element; so in your case, the required
rule will always be ignored. And since you have the min: 0
rule, you are getting a similar validation result that requires an item to be selected. Even with the value=""
attribute on the first option
, having both the required
and min
rules on a select
element makes no logical sense.
Here is the correct code...
HTML:
<select id="BusinessDistrictId" name="BusinessDistrictId">
<option value="">Select one...</option> <!-- first option contains value="" -->
//other options...
</select>
jQuery:
rules: {
BusinessDistrictId: { // <-- this is the name attribute
required: true
}
},
DEMO: http://jsfiddle.net/y82dV/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With