dstonek
dstonek

Reputation: 975

How to jQuery validate custom radio buttons

The form

<form id="form_reg" name="form_reg" method="post" action="">
      <input type="radio" id="y" name="opt" value="y"><label for="y"><span>YES</span></label>
      <input type="radio" id="n" name="opt" value="n"><label for="n"><span>NO</span></label>
      <button id="reg_submit" value=" " type="submit"></button>
</form>

JS Validation

$().ready(function() {
  $("#form_reg").validate({
        rules: {
          opt:{
              required: true
          }
        },
        messages: {
          opt: {
              required: "Select one "
          }
        }
  });


  $("#form_reg").validate();
})

This works good until I add CSS

input[type="radio"] {
    display:none;
}
input[type="radio"] + label span {
    width:27px;
    height:25px;
    background:url(/images/radio.svgz) no-repeat;
    cursor:pointer;
}
input[type="radio"]:checked + label span {
    width:27px;
    height:25px;
    background:url(/images/radio_a.svgz) no-repeat;
    cursor:pointer;
}

I guess this is because the default radio buttons are hidden.

How can I validate this form with these custom radio inputs?

Upvotes: 0

Views: 2790

Answers (1)

politus
politus

Reputation: 6086

To perform a validation on hidden fields you need to override the default 'ignore' setting with an empty array

$(function() {
  $("#form_reg").validate({
        ignore:[],
        rules: {
          opt:{
              required: true
          }
        },
        messages: {
          opt: {
              required: "Select one "
          }
        }
  });
});

Presumably you have a good reason to want to require a radio button that the user can't see. For instance when validating a form that is spread across several jquery ui tabs for instance, some fields may be hidden when the form is submitted.

Don't call validate twice on document ready also - although it does no harm there is no point the second call won't do much.

Upvotes: 3

Related Questions