0

I am trying to add a custom method to validate a group of radio buttons, using v1.9 of the jQuery validate plugin.

Contrary to this post, it is possible to have the same name attribute for radio button inputs, as long as any class rules are only applied to one of the inputs. jQuery validate then treats your input group as a single input.

This works when your inputs are children of a common parent, ie

<input type="radio" name="radiogroup" value="1" class="input-shipping" checked="checked">
<input type="radio" name="radiogroup" value="2">
<input type="radio" name="radiogroup" value="3">
<input type="radio" name="radiogroup" value="4">

But as soon as the html structure changes, the validation rules are not applied:

<div class="form-row">  
    <input type="radio" name="radiogroup" value="1" class="input-shipping" checked="checked">
</div>

<div class="form-row">          
    <input type="radio" name="radiogroup" value="2">
</div>

<div class="form-row">              
    <input type="radio" name="radiogroup" value="3">
</div>              

<div class="form-row">
    <input type="radio" name="radiogroup" value="4">        
</div>

Is anyone aware of a workaround for this issue? Class rules are added as follows:

$.validator.addClassRules({
    "input-shipping" : {
        required: true,
        dateselected: true
    }
});

$.validator.addMethod("dateselected", function(value, element) {
    console.log(element);
});

1 Answer 1

1

The reason the validation rule was not being called was that custom radio buttons were used, which set the CSS display value of inputs to none, and pseudo elements were styled up in place of the original inputs.

Once this was changed to visibility:hidden; the validator seemed to pick up the rule OK.

To create a custom method based on the value of the selected input, a further level of filtering was needed:

$.validator.addMethod("dateselected", function(value, element) {
    var radios = $('input[name='+element.name+']'),
    val = radios.filter(':checked')[0].value;
    console.log(val);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.