Reputation: 1522
I had a form that can send message and user need to select group from checkbox or manual input the group name. Now i want validate this form, if user not check any checkbox or insert any value in text field this form cannot sumbit.
Below is my form and here is my jsfiddle (already validate textarea).
<form action="" method="post" name="myform" id="myform">
<input type="checkbox" name="group_list[]" value="1" />Group 1<br />
<input type="checkbox" name="group_list[]" value="1" />Group 1<br />
<input type="checkbox" name="group_list[]" value="1" />Group 1<br />
<input type="checkbox" name="group_list[]" value="1" />Group 1<br />
<input type="text" name="manual_group" value="" placeholder="Group Name" /><br />
<textarea name="message" placeholder="Your Message"></textarea> <br />
<input type="submit" name="submit" value="Send Message" />
</form>
User need to check one of checkbox or insert group name before submit.So the question is how to create condition for this rule?
*Remember this form still can submit if i not check one of the checkbox but key-in some name in manual_group
, this form also can sumbit if i not key-in any name but check for checkbox.
Upvotes: 0
Views: 2326
Reputation: 6086
You can achieve this by setting a rule on the textbox that it is required only if none of the checkboxes are checked. This uses the type of required specification that takes a function as a parameter.
rules: {
manual_group: {
required: function () {
return $('[name=group_list\\[\\]]:checked').length === 0;
}
}
}
The other thing you need to do is force a re-validation when either the checkboxes or the textbox are changed. I have done it like this,
$('form input').on('click focusin focusout keyup', function () {
$('form').validate().form();
});
The full script is below, and in this fiddle
$(function () {
$("form").validate({
rules: {
manual_group: {
required: function () {
return $('[name=group_list\\[\\]]:checked').length === 0;
}
}
},
messages: {
manual_group: "Please check a checkbox or fill in this field"
},
submitHandler: function () {
alert('form ok');
}
});
$('form input').on('click focusin focusout keyup', function () {
$('form').validate().form();
});
});
Upvotes: 1
Reputation: 426
May be this will work
$("#submit").click(function(){
if($('#myform input:checked').length >= 1 || $("#manual_group").val() !=""){
return true ;
}
return false;
}
Upvotes: 0
Reputation: 5989
with reference to your Fiddle
you can add it in the same way just like the validation you'hv added for message
e.g.
"group_list[]": {required:true}...
Upvotes: 0