Click Submit with no option selected to see the validation message. Then choose an option and submit again.
const selected = document.querySelector('input[name="gender"]:checked');
if (!selected) {
message.textContent = "Please select one radio button before submitting.";
return;
}
message.textContent = `Validation passed. Selected value: ${selected.value}`;
<label><input type="radio" name="gender" value="male"> Male</label>
<label><input type="radio" name="gender" value="female"> Female</label>
<button type="submit">Submit</button>
Radio button validation tutorial
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.