Skip to main content
J Cellini
Inspiring
July 27, 2009
Question

Validate Drop-Down Menu on PHP From

  • July 27, 2009
  • 1 reply
  • 910 views

I am trying to validate drop-down menus on a PHP form. I think I am close to a solution, I just need a little guidance from a seasoned pro.

The first drop-down menu has just three options: Select One, Standard, and Custom. The visitor must select either Standard or Custom.

I actually came up with something that works, but it displays an error on the initial form. Here's what I have:

In the head above the doc type declaration, I created the following array:

// validate drop-down menus

$report_type_choices = array('Standard', 'Custom');

The select id is "report_type". Here's what I have in the body:

<?php
    if (! in_array($_POST['report_type'], $report_type_choices)) {?>
    <p><span class="warning">You must select a Report Type.</span></p><?php }
?>

This actually works. If I ignore the messy error and I click submit when either Standard or Custom is selected, I get a confirmation and a clean page. If I do not select "Standard" or "Custom", I get my warning "You must select a Report Type" but the page is clean - no error. The error only shows in the initial page (the following error is linked to a web page):

Warning:  in_array() [function.in-array]: Wrong datatype for second argument in /home/jcellini/public_html/elanwebservices/req_form/req_form2.php on line 160

So, the only apparent problem is the display of the error. The PHP manual suggests add this line of code in front of the ! in_array:

sizeof($report_type) == 0 ||

So, the code becomes:

<?php

if (sizeof($report_type) == 0 || ! in_array($_POST['report_type'], $report_type_choices)) {?>
    <p><span class="warning"><You must select a Report Type.</span></p><?php }

?>

This actually gets rid of the error but displays the warning on the initial form ("You must select a Report Type"), which I don't want. I am also wondering why my $report_type array is empty (if that is what the error is suggesting).

So, I think I am close, I just need some advice.

This topic has been closed for replies.

1 reply

J Cellini
J CelliniAuthor
Inspiring
July 28, 2009

In case this can be useful to someone else, I found a solution that works. Here is the validation code:

<?php
    if (sizeof($report_type) == 0 || in_array($_POST['report_type'], $report_type_choices)) {
    } else {?>
    <p><span class="warning">You must select a Report Type.</span></p><?php
    }
?>

This works and does what I want it to do, but in case someone has a better way or sees any problem with the code, please let me know.