Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery validate - User must select YES radio (not no) in order to conitnue

I would like to set up a jQuery validate rule to require that YES (not no) be checked in order for the form to validate/submit. User must accept terms. If the user selects no they will get the error msg and the form will not validate. What is the correct way to accomplish this using jquery validate plugin?

<form id="myForm">
<input type="radio" name="terms" id="terms1" value="Yes!" class="required" title="Must accept terms to continue" /> Yes
<input type="radio" name="terms" id="terms2" value="No" class="required" title="Must accept terms to continue" /> No
</form>

$("#myForm").validate({ 

/*
Insert your awesome jquery validation code here. Free beer to whoever answers the question!
*/

}); 

Here is a working example: http://jsfiddle.net/ThcS8/1/

Kudos to anyone who can provide a solution or even better an example! Vote this up if you are looking for the same solution so it gets attention. Thanks all!

Please vote for your favorite solution!

like image 725
chainwork Avatar asked Oct 13 '11 18:10

chainwork


3 Answers

I also had this problem, and tried various things including the solutions mentioned above. In the end I wrote a custom validator method to check for a required value in a radio button:

jQuery.validator.addMethod("requiredRadioValue", function(value, element, params) { 
    var selectedValue = $('input:radio[name=' + element.name + ']:checked').val(); 
    return (typeof(params) == 'array') ? (params.indexOf(selectedValue) != -1) : selectedValue == params;
}, "You must select the required option."); 

The method is used e.g.

signedcif: { requiredRadioValue: 'yes' }

the allowed options can be an array or single value.

Hope this helps, I was hoping this wasn't the most straight-forward way to do this, so any alternatives gratefully received!

like image 151
purelylogical Avatar answered Sep 27 '22 02:09

purelylogical


You should remove the required from the no input radio and then simply do

$("form").validate(); 

this initializes the jquery validation. It will see the yes is required to be selected and won't let the form submit until it is.

like image 40
Keith.Abramo Avatar answered Sep 23 '22 02:09

Keith.Abramo


change the value from true and false to 1 and 0 respectively. and add rule for

$('form').validate({
rules:{
    terms: {min:1}
},
messages:{
    terms: {min:'you must accept terms to move on.'}
}
});
like image 22
Funky Dude Avatar answered Sep 24 '22 02:09

Funky Dude