<form name="Stumarks" action="lala.php" method="GET">
Semester: <br />
<input type="radio" name="semester" value="1" />Fall<br />
<input type="radio" name="semester" value="2" />Spring<br />
<input type="submit" value="submit"/>
</form>
I want those to be validated so that if the user did not select one, then the data will be redirected to this original form with an error message beside the radio buttons.
How do i validate radio button? PHP
Moderator: General Moderators
-
TheDumbNerd
- Forum Newbie
- Posts: 13
- Joined: Sun Nov 13, 2011 4:01 pm
Re: How do i validate radio button? PHP
check $_POST['semester'] value. if > 0 display error message 
-
TheDumbNerd
- Forum Newbie
- Posts: 13
- Joined: Sun Nov 13, 2011 4:01 pm
Re: How do i validate radio button? PHP
I don't understand what you mean by that?bampera wrote:check $_POST['semester'] value. if > 0 display error message
Re: How do i validate radio button? PHP
Two problems with that:check $_POST['semester'] value. if > 0 display error message
1. if ($_POST['semester'] > 0, that means they DID pick one, not an error.
2. If they do not pick any radio buttons, $_POST['semester'] will NOT exist when you submit the form. (same for checkboxes BTW)
Most basic:
Code: Select all
if (!isset[$_POST['semester']) {
// ERROR
}Code: Select all
$intSemester = (isset($_POST['semester'])) ? (int)$_POST['semester'] : FALSE;
if (!$intSemester) {
// ERROR
}Code: Select all
foreach(array('semester','year','accept-terms') as $index) {
if (!isset($_POST[$index])) { $_POST[$index] = FALSE; }
}-
TheDumbNerd
- Forum Newbie
- Posts: 13
- Joined: Sun Nov 13, 2011 4:01 pm
Re: How do i validate radio button? PHP
twinedev wrote:Two problems with that:check $_POST['semester'] value. if > 0 display error message
1. if ($_POST['semester'] > 0, that means they DID pick one, not an error.
2. If they do not pick any radio buttons, $_POST['semester'] will NOT exist when you submit the form. (same for checkboxes BTW)
Most basic:if you are assigning it to another variable first though:Code: Select all
if (!isset[$_POST['semester']) { // ERROR }If you have a bunch of radios / checkboxes on the form, try the following right at the top before validating. The values in array() are a list of radio/checkbox namesCode: Select all
$intSemester = (isset($_POST['semester'])) ? (int)$_POST['semester'] : FALSE; if (!$intSemester) { // ERROR }Code: Select all
foreach(array('semester','year','accept-terms') as $index) { if (!isset($_POST[$index])) { $_POST[$index] = FALSE; } }
What about if I wanted to show an error message if the user did not select any of the options?
Re: How do i validate radio button? PHP
TheDumbNerd wrote:What about if I wanted to show an error message if the user did not select any of the options?
twinedev wrote: 2. If they do not pick any radio buttons, $_POST['semester'] will NOT exist when you submit the form. (same for checkboxes BTW)
Most basic:Code: Select all
if (!isset[$_POST['semester']) { // ERROR }