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

泄露秘密 提交于 2019-12-22 06:47:34

问题


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!


回答1:


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!




回答2:


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.




回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/7758931/jquery-validate-user-must-select-yes-radio-not-no-in-order-to-conitnue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!