132

How to perform validation for a radio button group (one radio button should be selected) using jQuery validation plugin?

user27052
  • 375
  • 3
  • 8
  • 12
  • Out there is a new jQuery validator that is very powerfull and easy to use. You can check it out: http://code.google.com/p/bvalidator/ – Nenad Jan 13 '11 at 13:01
  • don't want to include entire a library for something as simple as this – Doug Molineux Feb 03 '11 at 19:07
  • Look the answer from c.reeves in http://forum.jquery.com/topic/jquery-validate-plugin-radio-buttons-dependent-fields –  Nov 29 '10 at 18:01

8 Answers8

116

With newer releases of jquery (1.3+ I think), all you have to do is set one of the members of the radio set to be required and jquery will take care of the rest:

<input type="radio" name="myoptions" value="blue" class="required"> Blue<br />
<input type="radio" name="myoptions" value="red"> Red<br />
<input type="radio" name="myoptions" value="green"> Green

The above would require at least 1 of the 3 radio options w/ the name of "my options" to be selected before proceeding.

The label suggestion by Mahes, btw, works wonderfully!

Brandon Rome
  • 61
  • 1
  • 2
  • 5
  • This is now the best answer for me with the updates to jQuery. +1. – Kieran Andrews Feb 21 '11 at 01:46
  • 6
    The only problem with this is when none of them are checked, jQuery validate highlights the first radio button in red, but in reality you probably want to highlight ALL of them. Also, once you check any radio button, the red should go away. – Haacked Apr 10 '11 at 17:19
  • 2
    @Haacked You could use the errorPlacement callback function in the validation options to place the error message somewhere meaningful? – autonomatt Sep 12 '11 at 20:24
  • 2
    @Haacked: adding `focusInvalid: false` to the `validate()` options will prevent the highlighting of the first radio button. – Jim Miller Nov 30 '12 at 20:26
  • 2
    I always do it this way and position the error label in the errorPlacement function. This is what I do for radio buttons: if (element.is("input:radio")) { error.insertAfter(element.parent()); } else { error.insertAfter(element); } – Francisco Goldenstein Nov 14 '14 at 20:23
  • @Haacked probably late now but if you put required to ALL jQuery will highlight all of them and will validate when one is checked – Juanjo Oct 10 '16 at 16:32
26

use the following rule for validating radio button group selection

myRadioGroupName : {required :true}

myRadioGroupName is the value you have given to name attribute

Mahes
  • 3,938
  • 1
  • 34
  • 39
  • 15
    Note that if you want to control the position of the label, you can provide your own error label where you want it with the text you would like: – Tom Apr 09 '10 at 02:02
  • @Tom it's useless to write yourself the `label` tag for the error, actually the plugin adds automatically this error label tag. – ahmehri May 06 '15 at 10:26
  • 3
    Rather a long time ago, but I imagine what I was trying to do was to place the – Tom May 07 '15 at 12:19
  • Sad how it requires the "name" instead of the "type" here for custom errors. – justdan23 Apr 02 '20 at 19:39
21

You can also use this:

<fieldset>
<input type="radio" name="myoptions[]" value="blue"> Blue<br />
<input type="radio" name="myoptions[]" value="red"> Red<br />
<input type="radio" name="myoptions[]" value="green"> Green<br />
<label for="myoptions[]" class="error" style="display:none;">Please choose one.</label>
</fieldset>

and simply add this rule

rules: {
 'myoptions[]':{ required:true }
}

Mention how to add rules.

koral
  • 2,807
  • 3
  • 37
  • 65
Haider Abbas
  • 1
  • 1
  • 2
  • 1
    But this would bring errors on HTML5 validation I believe as the for attribute needs to be an ID reference (which we can't set 3 radio button's to the same ID). – armyofda12mnkeys Aug 06 '12 at 16:28
  • 1
    There is a BIG difference between the name attribute and the id attribute. – Norman H Dec 31 '12 at 19:31
  • 2
    Please not that a radio button should return only one value, therefor, the `name="myoptions[]"` is a bit confusing since it hints multiple values can be returned. – Rafael Herscovici Jan 26 '15 at 10:35
  • Puts the error message on top.
    Blue
    Red
    Green
    – Sonobor Apr 30 '19 at 21:25
6

As per Brandon's answer. But if you're using ASP.NET MVC which uses unobtrusive validation, you can add the data-val attribute to the first one. I also like to have labels for each radio button for usability.

<span class="field-validation-valid" data-valmsg-for="color" data-valmsg-replace="true"></span>
<p><input type="radio" name="color" id="red" value="R" data-val="true" data-val-required="Please choose one of these options:"/> <label for="red">Red</label></p>
<p><input type="radio" name="color" id="green" value="G"/> <label for="green">Green</label></p>
<p><input type="radio" name="color" id="blue" value="B"/> <label for="blue">Blue</label></p>
Matt Frear
  • 52,283
  • 12
  • 78
  • 86
3

Another way to validate is like this.

var $radio = $('input:radio[name="nameRadioButton"]');
$radio.addClass("validate[required]");

I hope my example will help you

2

code for radio button -

<div>
    <span class="radio inline" style="margin-right: 10px;">@Html.RadioButton("Gender", "Female",false) Female</span>
    <span class="radio inline" style="margin-right: 10px;">@Html.RadioButton("Gender", "Male",false) Male</span>
    <div class='GenderValidation' style="color:#ee8929;"></div>
</div>

<input class="btn btn-primary" type="submit" value="Create" id="create"/>

and jQuery code-

$(document).ready(function () {
    $('#create').click(function(){
        var gender=$('#Gender').val();

        if ($("#Gender:checked").length == 0) {
            $('.GenderValidation').text("Gender is required.");
            return false;
        }
    });
});
Mr.Singh
  • 1,421
  • 6
  • 21
  • 46
Sayli Vaidya
  • 179
  • 1
  • 14
2

I had the same problem. Wound up just writing a custom highlight and unhighlight function for the validator. Adding this to the validaton options should add the error class to the element and its respective label:

        'highlight': function (element, errorClass, validClass) {
            if($(element).attr('type') == 'radio'){
                $(element.form).find("input[type=radio]").each(function(which){
                    $(element.form).find("label[for=" + this.id + "]").addClass(errorClass);
                    $(this).addClass(errorClass);
                });
            } else {
                $(element.form).find("label[for=" + element.id + "]").addClass(errorClass);
                $(element).addClass(errorClass);
            }
        },
        'unhighlight': function (element, errorClass, validClass) {
            if($(element).attr('type') == 'radio'){
                $(element.form).find("input[type=radio]").each(function(which){
                    $(element.form).find("label[for=" + this.id + "]").removeClass(errorClass);
                    $(this).removeClass(errorClass);
                });
            }else {
                $(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);
                $(element).removeClass(errorClass);
            }
        },
Cin
  • 86
  • 4
0

Puts the error message on top.

.radio-group {
    position: relative;
    margin-top: 40px;
} 

#myoptions-error {
    position: absolute; 
    top: -25px;
}
<div class="radio-group"> 
    <input type="radio" name="myoptions" value="blue" class="required"> Blue<br /> 
    <input type="radio" name="myoptions" value="red"> Red<br /> 
    <input type="radio" name="myoptions" value="green"> Green
</div><!-- end radio-group -->
Mr.Singh
  • 1,421
  • 6
  • 21
  • 46
Sonobor
  • 301
  • 3
  • 3