form validation using arrays

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
nevx009
Forum Newbie
Posts: 3
Joined: Sat Nov 14, 2009 1:38 pm

form validation using arrays

Post 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
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: form validation using arrays

Post 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
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply