Forums

Server Side Validation "partially" not working

v-g 04 Nov, 2009
Hello! This is my first post on here.

I will begin with saying ChronoForms is a lovely component. Very easy to understand and set up!

So to my question:

I've this code set up:

<?php
  // delete all non allowed parameters
  $allowed_vars = array('Etternavn', 'Fornavn', 'Mobil', 'E-postadresse');
  foreach (array_keys($_POST) as $var) {
      if (! in_array($var, $allowed_vars)) {
          unset($_POST[$var]);
      }
  }
 
  // validate: not empty
  foreach ($allowed_vars as $var) {
      if (empty($_POST[$var])) {
          return 'Alle obligatoriske felt må fylles inn.';
      }
  }
 
  // return nothing to mark submitted values as valid
?>


I want 4 fields to be filled and to be warned if not filled. If I fill in the 4 fields in question, I still get the message saying all marked fields need to be filled.

What have I missed?

Thanks
nml375 04 Nov, 2009
Hi,
The thoughts that comes to mind, is the case sensitivity of array indexes. As such, your $allowed_vars array must match your form field names in case. Other than that, the code looks proper. You could try and add $var to your error reason, to indicate which field failed. You could also consider including a print_r() of the $_POST variable.

<?php
  // delete all non allowed parameters
  $allowed_vars = array('Etternavn', 'Fornavn', 'Mobil', 'E-postadresse');
  foreach (array_keys($_POST) as $var) {
      if (! in_array($var, $allowed_vars)) {
          unset($_POST[$var]);
      }
  }

  // validate: not empty
  foreach ($allowed_vars as $var) {
      if (empty($_POST[$var])) {
          return 'Alle obligatoriske felt må fylles inn: ' . $var . '<br />' . print_r($_POST, true);
      }
  }

  // return nothing to mark submitted values as valid
?>

/Fredrik
GreyHead 04 Nov, 2009
Hi v-g.

It's late here but I think the logic fails if any of the allowed_vars aren't set as you are still checking them after the $_POST values are unset. Try
<?php
// delete all non allowed parameters
$allowed_vars = array('Etternavn' => '', 'Fornavn' => '', 'Mobil' => '', 'E-postadresse' => '');
$posted = JRequest::get('post');

// drop all entries from $posted unless the key matches
$posted = array_intersect_key($posted, $allowed_vars);

// validate: not empty
foreach ( $posted as $k => $v ) {
  if ( !$v ) {
    return 'Alle obligatoriske felt må fylles inn.';
  }
}
// return nothing to mark submitted values as valid
?>

Bob
v-g 04 Nov, 2009
Thanks for the swift replies guys!

Bob, your code did the trick! 😀 (I used text_1 etc instead)

G'nite!
This topic is locked and no more replies can be posted.