Single Selection Validator

Validate option groups. Prevents form submission if the user has neglected to pick an option from a required radio button list.

Please rate our service:

Copy the Script

<script>
function validateRadios() {
    var radios = document.getElementsByName("options");
    var formValid = false;

    var i = 0;
    while (!formValid && i < radios.length) {
        if (radios[i].checked) formValid = true;
        i++;
    }

    if (!formValid) {
        alert("Please make a selection!");
        return false;
    }
    return true;
}
</script>

<form onsubmit="return validateRadios()">
    <input type="radio" name="options" value="A"> A
    <input type="radio" name="options" value="B"> B
    <button type="submit">Go</button>
</form>

Frequently Asked Questions

Unlike text inputs which have a simple `.value` property, radio buttons are a collection. You must iterate through them to see if any have `checked === true`.

Yes. If you add `checked` to one of your HTML radio tags, validation is technically unnecessary because one is always selected.

Yes, but for checkboxes you typically want to validate that *at least one* (or a specific number) is checked, rather than exactly one.