How Can I Make A Radio Button Required?

I am building a form in PHP and am working on the validation process. How can I make an option that has two radio buttons required?

When the page loads, neither option is selected. If the visitor doesn’t select an option, I would like it to be able to detect this but I can’t figure it out. I’ve figured out how to do do a textfield,textarea, and select box, but I can’t figure out the radio button. I’ve searched Google and I can’t find anything on this.

I’ve tried this but it doesn’t work:

Type: <input type="radio" name="type" value="New" <? if ($type == "New") { print("checked"); }?>> New
<input type="radio" name="type" value="Old" <? if ($type == "Old") { print("checked"); }?>> Old

Any help would be greatly appreciated.

When the page loads why not just make one radio button “checked” by default?

I may have missed the point here but here goes anyway!

Your radio button code looks like this:

<input type="radio" name="type" value="New">
<input type="radio" name="type" value="old">

and you have two of them, with the values new and old…

When you submit the form it creates the variable $type and this either holds the value new, old or isn’t created becuase the user hasn’t selected either.

Is this what your after then?..


if (!isset($type)) {
     echo("Error: please specify a type, new or old");
     exit();

} else {

// continue with the form validation code

}

This would check if $type had been set, and if not would spit out the error, Error: please specify a type, new or old, and stop the script, if the variable was set then it would continue with the script.

Hope this helps, and I havn’t missed the point :wink:

Rick :slight_smile:

Thanks Rick,

That worked!

No problem.

Good luck with the rest of your project :slight_smile:

Rick