I'm using jquery validate and it works with the normal fields. I need a way to make sure there is at least one entry in the one listbox before validation is satisfied. I tried to add a custom method.
$.validator.addMethod('checklist', function(value, element) {
if ($("#currentimp").val() ==""){
return false;
} else return true;
}, "Listbox is empty");
Then in the rules i have the following:
currentimp: {
checklist:true
}
I'm not sure if there is a better way to accomplish this but I haven't seen any good examples for what I'm trying to do. I also changed my form button to a submit button but it won't submit unless I add in a submit function to the submithandler. Is this normal?
如果列表框是某种选择框或单选框,则只需使用required:true
规则,而无需创建自己的自定义规则。
Quote OP :
"I need a way to make sure there is at least one entry in the one listbox before validation is satisfied."
If by "listbox", you mean <select multiple="multiple">
, then you do not need to write a custom method; you'd use the required
rule.
The trick with validating a select
is that your first <option>
must contain value=""
.
HTML :
<select name="currentimp" id="currentimp" multiple="multiple">
<option value="">...</option>
<option value="1">option 1</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
<option value="4">option 4</option>
</select>
jQuery :
$(document).ready(function () {
$('#myform').validate({
rules: {
currentimp: {
required: true
}
}
});
});
DEMO: http://jsfiddle.net/5GKbF/
Quote OP :
"I also changed my form button to a submit button but it won't submit unless I add in a submit function to the submithandler. Is this normal?"
No, this is not normal.
The jQuery Validate plugin will always capture the click of any button with type="submit"
as long as it's contained within your <form></form>
tags.
Both <input type="submit" ...
and <button type="submit" ...
are acceptable.
The submitHandler
callback is not a mandatory option.
If you leave out the submitHandler
callback option, upon successful validation, the form will submit to the URL specified within your action
attribute.
<form action="myScript.php" ...
Typically, the submitHandler
is only used when you want to bypass the action
and submit the form via .ajax()
, and/or perform some other function(s).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.