I have a form with three fields - a text field (name), option field (position) and radio field (visible). My radio field is a true/false value, so my database is storing it as a tinyint. Therefore, the value of the radio buttons are 0 and 1.
Now in comes validation. I want to make sure that all fields are filled out, including the radio buttons since they are necessary for the database query. If the user clicks the false radio button, the value passed in through the post is 0. This is a problem.
if (isset($_POST['submit'])) {
$errors = array();
$required_fields = array('name', 'position', 'visible');
foreach ($required_fields as $field) {
if (!isset($_POST[$field]) || (empty($_POST[$field]) && $_POST[$field] != 0)) {
$errors[] = $field;
}
}
.
.
.
By adding the && $_POST[$field] != 0 expression, I fix the problem of the radio button being a 0. However, for some reason I'm always getting an error which I can't make sense of. EDIT: I've had so many problems with this validation that I got my errors mixed up. With the above code, the problem comes in when I leave the text field (name) completely empty. For some reason, this is OK and the query succeeds with an empty name field. This is a problem.
Looking at the code it would seem as though the text field would NOT be set (if (!isset($_POST[$field])), and the if block would execute to add an error to the array. Or, if it is set, then wouldn't it be empty() AND not be equal to 0? Am I missing something?
EDIT: Wow, I'm confused. I added the line,
echo ($_POST['name'] == 0) ? "1" : "0";and it's coming back that name == 0 no matter if there's text in it or not.
Edited by crippled, 09 July 2010 - 07:51 PM.


Sign In
Create Account


Back to top









