Jump to content

Radio Button Validation


Fmdpa

Recommended Posts

I know it sounds simple, but I've tried MANY combinations of code, and none of them are successfully checking whether a radio button is selected. I don't want to choose a default radio button, because I want to ensure that the user DOES select an option.

$radio = $_POST['radio_input'];if($_POST['submit']) {	if($radio == '') { //method no. 1		//error   }   	if(($radio != 'option1') && ($radio != 'option2') && ($radio != 'option3')) { //method no. 2		//error   }	if(!$radio) { //method no. 3		//error   }	  	if(empty($radio)) { //method no. 4		//error   }   }

What could be wrong?

Link to comment
Share on other sites

It's kind of hard to tell without seeing the form markup, but keep in mind that browsers only submit checkboxes and radio buttons if they are selected. If they are not selected, the browser doesn't even submit something with that name. You can use the isset function to check if something in $_POST is set.

Link to comment
Share on other sites

yes, but that's assuming $_POST is set. That's what you need first before you can start assigning variables from it.

Link to comment
Share on other sites

Since $radio is set to the $_POST value, isn't that indirectly checking $_POST?
isset checks if a variable is set. $radio is set to some value from $_POST, which may not be set. If the value in $_POST is not set, $radio will get set to an empty string. So $radio is set, but the value in $_POST is not. So no, it's not indirectly checking if $_POST is set, it's directly checking if $radio is set. The empty function will return true if the value is either not set or empty.
Link to comment
Share on other sites

Here's the final working code:

global $radio;$radio = isset($_POST['radio']) ? $_POST['radio'] : '';if ($radio != '') {		switch ($radio) {			case 'landscape':				//process landscape				break;			case 'wildlife':				//process wildlife				break;			case 'other':				//process other				break;		} //end switch statement	} //end radio button processif ($radio == '') {	$errors .= 'Please Select a Category.<br/>';}//end validate

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...