开发者

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开发者_如何学JAVA 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!


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!


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.


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.'}
}
});


Assuming the checkbox has the class 'required' and has the name 'agreeForm', here is something that could work:

   jQuery("#regForm").validate({
      debug: true,
      rules: {
        agreeForm: "required",
      },
      messages: {
        agreeForm: "Please accept our Terms and Conditions.",
      }
    });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜