Page 1 of 1

form validation using arrays

Posted: Thu Dec 03, 2009 7:51 am
by nevx009
i need help with this form validation


if (isset($_POST['submit'])) {
$errors = array();

$required_fields = array('menu_name', 'position','visible');
foreach($required_fields as $fieldname) {
if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) {
$errors[] = $fieldname;
}
}
$fields_with_lengths = array('menu_name' => 30);
foreach($fields_with_lengths as $fieldname => $maxlength ) {
if (strlen(trim(mysql_prep($_POST[$fieldname]))) > $maxlength) { $errors[] = $fieldname; }
}

if (empty($errors)) {
// Perform Update
$id = mysql_prep($_GET['subj']);
$menu_name = mysql_prep($_POST['menu_name']);
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
//update code
}
}

<form action="edit_subject.php?subj=<?php //myvalue passing here for the id you click on ?>" method="post">
<p>Subject name:
<input type="text" name="menu_name" value="<?php echo $sel_subject['menu_name']; ?>" id="menu_name" />
</p>

<input type="submit" name="submit" value="Edit Subject" />
</form>


the problem is that if don't enter something in the input type="text" the form still updates the subject to blank , now if i try submit again with a blank value the form doesn't go to update part which is what i want , but should not allow any blank values passing in the first place , so the array above is not empty, how can i achieve this using this arrays as above
any help greatly appreciated

Re: form validation using arrays

Posted: Thu Dec 03, 2009 11:16 am
by AbraCadaver
I haven't tested your code, but just a quick look shows that you really don't need the isset() because it will be set if the form is submitted (unless someone is circumventing your form) and you don't need !=0 because if it is 0 then it will be empty(). So you might try trimming the POST var and see:

Code: Select all

foreach($required_fields as $fieldname) {
   $value = trim($_POST[$fieldname]);
   if (empty($value)) {
      $errors[] = $fieldname;
   }
}

-Shawn