Reputation: 9
Okay so I have a form and within this form are a bunch of required fields. The birthday part of this form consists of 3 fields: month, day, and year. Now what I want to do is have the words "Month:", "Day:", and "Year:" at the top of the drop down lists, BUT I do not want these options to be acceptable answers! When I submit the form without selecting an actual month, day, and year, it should say that the month, day, and year are required when I print the errors! How can I accomplish that? My "if statements" that make the fields required are at the bottom of this code:
<form action="" method="post">
<ul id="register">
<li>
Birthday:
<select name="month">
<option value="month">Month:</option>
<option value="January">January</option>
//all the other months
</select>
<select name="day">
<option value="day">Day:</option>
<option value="1">1</option>
//all the other days of the month
</select>
<select name="year">
<option value="year">Year:</option>
<option value="2013">2013</option>
//more year options
</select><br><br>
</li>
<li>
<input type="submit" name="registrationform" value="Sign up">
</li>
</ul>
</form>
<?php
if (!empty($_POST['registrationform'])) {
if(isset($_POST['registrationform'])){
$required_fields = array('month', 'day', 'year');
foreach ( $required_fields as $key=>$value) {
if (!isset($_POST[$value]) || $_POST[$value]=='') {
$errors[$value] = $key." is required";
}
}
print_r($errors);
}
}
?>
Upvotes: 0
Views: 3554
Reputation: 12581
Use optgroup
<select name="month">
<optgroup label="Month:">
<option value="January">January</option>
//all the other months
</optgroup>
</select>
etc.
or disable the option and select the title if you want the title to show - once the list is touched, the title will not be selectable.
<select name="month">
<option disabled="disabled" selected="selected">Month:</option>
<option value="January">January</option>
//all the other months
</select>
Upvotes: 3
Reputation: 396
I agree with PassKit but please add some validation to your code
if (!is_int($_POST[$value])) {
// not valid
}
And dont post months as January but as 1 .. 12 since it much safer and easier to validate
Upvotes: 1