jQuery select box validation
jquery, jquery-validate
Solution
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>
Demo: http://jsfiddle.net/XGtEr/
Problem
I have following code in jQuery. I need to display a validation message "Year Required" when the option value of `select` element is "0". ``` <script type="text/javascript"> $(document).ready(function () { $("#register").validate({ debug: true, rules: { year: { required: function () { if ($("#year option[value='0']")) { return true; } else { return false; } } } }, messages: { year: "Year Required", }, }); }) </script> ``` Select box ``` <select name="year" id="year"> <option value="0">Year</option> <option value="1">1919</option> <option value="2">1920</option> <option value="3">1921</option> <option value="4">1922</option> </select> ```