jQuery select box validation
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>
Solution 1:
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/
Solution 2:
To put a require rule on a select list you just need an option with an empty value
<option value="">Year</option>
then just applying required on its own is enough
<script>
$(function () {
$("form").validate();
});
</script>
with form
<form>
<select name="year" id="year" class="required">
<option value="">Year</option>
<option value="1">1919</option>
<option value="2">1920</option>
<option value="3">1921</option>
<option value="4">1922</option>
</select>
<input type="submit" />
</form>
fiddle is here
Solution 3:
http://docs.jquery.com/Plugins/Validation/Methods/required
edit the code for 'select' as below for checking for a 0 or null value selection from select list
case 'select':
var options = $("option:selected", element);
return (options[0].value != 0 && options.length > 0 && options[0].value != '') && (element.type == "select-multiple" || ($.browser.msie && !(options[0].attributes['value'].specified) ? options[0].text : options[0].value).length > 0);