Search code examples
javascripthtmlradio-buttonradio-grouprequired

How to check if radio button group is required


I have a dynamic radio button group where the required attribute may not be specified on all inputs.

<form name="myform">
    <input type="radio" id="option1" name="foo" value="First" >
    <input type="radio" id="option2" name="foo" value="Second" required>
    <input type="radio" id="option3" name="foo" value="Third">
    <input type="radio" id="option4" name="foo" value="Fourth">
</form>

Is there a way to check in JavaScript whether the radio button group is required without iterating through all inputs in the group?

I have looked at input element's validity.missingValue property which works when no radio button is selected but I have no solution for when the field is valid. Currently I have the following code, but it would be nice if there was some other property to use e.g. on the HTMLInputElement or RadioNodeList.

function isRequired() {
    return Array.from(document.myform.foo).some(i => i.required)
}

Solution

  • Maybe something like that ?

    const myForm = document.forms['my-form'];
    
    console.log( !!myForm.querySelector('input[name="foo"][required]') )  // true
    <form name="my-form">
      <input type="radio" name="foo" value="First" >
      <input type="radio" name="foo" value="Second" required >
      <input type="radio" name="foo" value="Third" >
      <input type="radio" name="foo" value="Fourth" >
    </form>

    You can also add a "dirty wrapper":

    // define new getter property (dirty wrapper)
    RadioNodeList.prototype.__defineGetter__( 'isRequired', function(){ return [...this].some(r=>r.required) });
    
    const myForm = document.forms['my-form'];
    
    console.log(  myForm.foo.isRequired ); // true
    <form name="my-form">
      <input type="radio" name="foo" value="First">
      <input type="radio" name="foo" value="Second" required>
      <input type="radio" name="foo" value="Third">
      <input type="radio" name="foo" value="Fourth">
    </form>