Since you cannot set value=""
within your first option
, you’ll need to create your own rule using the built-in addMethod()
method.
jQuery:
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
year: {
selectcheck: true
}
}
});
jQuery.validator.addMethod('selectcheck', function (value) {
return (value != '0');
}, "year required");
});
HTML:
<select name="year">
<option value="0">Year</option>
<option value="1">1955</option>
<option value="2">1956</option>
</select>
Working Demo: http://jsfiddle.net/tPRNd/
Original Answer: (Only if you can set value=""
within the first option
)
To properly validate a select
element with the jQuery Validate plugin simply requires that the first option
contains value=""
. So remove the 0
from value="0"
and it’s fixed.
jQuery:
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
year: {
required: true,
}
}
});
});
HTML:
<select name="year">
<option value="">Year</option>
<option value="1">1955</option>
<option value="2">1956</option>
</select>