Asked  7 Months ago    Answers:  3   Viewed   24 times

This question will undoubtedly be difficult to answer and ask in a way that makes sense but I'll try my best:

I have a form which uses PHP to display certain sections of the form such as:

<?php if ($_SESSION['EnrType'] == "Individual") { display only form information for individual enrollment } ?>

and

<?php if ($_SESSION['Num_Enrs'] > 6) { display only form information for 7 total members enrollment } ?>

In each form piece, unique information is collected about each enrollee but the basic criteria for each enrollee is the same, i.e. All enrollee's must use have a value in the FirstName field. Each field is named according to the enrollee number, i.e. Num1FirstName; Num2FirstName.

I have a PHP validation script which is absolutely fantastic and am not looking to change it but the issue I am running into is duplication of the script in order to validate ALL fields in one swoop.

On submission, all POSTED items are run through my validation script and based on the rules set return an error if they do not equal true.

Sample code:

if (isset($_POST['submit']))
{
  // import the validation library
  require("validation.php");

  $rules = array(); // stores the validation rules

  //All Enrollee Rules
  $rules[] = "required,Num1FirstName,Num2FirstName,The First Name field is required.";

The script above does the following, $rules[] ="REQUIREMENT,fieldname,error message" where requirement gives criteria (in this case, simply that a value is passed), fieldname is the name of the field being validated, and error message returns the error used.

My Goal is to use the same formula above and have $rules[] run through ALL firstnames and return the error posted ONLY if they exist (i.e. dont check for member #7's first name if it doesnt exist on the screen).

If I simply put a comma between the 'fieldnames' this only checks for the first, then second, and so on so this wont work.

Any ideas?

 Answers

42

If I understand what you're trying to do correctly:

1. Define types
First, you need to define what type of field requires what kinds of rules, e.g.:

$type['FirstName']['requirement'] = 'required';
$type['FirstName']['error_message'] = 'The First Name field is required.';
// just random example: $type['MobilePhone']['requirement'] = 'optional'; $type['MobilePhone']['error_message'] = 'Only enter digits.';

2. Go through each posted value
Second, check for each posted value what type of field it is. Now a lot of stuff might be included in the $_POST array, and you only need to check certain fields. It might make it a lot easier to use names like checkthis;1234;FirstName for your input fields.

foreach ($_POST as $key => $value) {
  // split the key, so you know what's what:
  $data = explode(';',$key);
// now $data[0] tells you what kind of field it is // $data[1] is the ID of the enrollee (your Num1, Num2) // $data[2] is the type of field
// only do checks for posted fields that start with "checkthis" if ($data[0]=='checkthis') { // now you can fill the $rule array: $rule[] = $type[$data[2]]['requirement'] . ',' . $key . ',' . $type[$data[2]]['error_message']; } }
This way it doesn't matter what you include in your form. As long as you've defined the type of field, a rule will be added to the rule array if it's included in the $_POST values, and your validation script will do the rest.


Edit
If you structure your input fields like this:


<input type="text" name="F1Firstname" value="" />
<input type="text" name="F2Firstname" value="" />
etc..

..and you submit the form, the $_POST array will e.g. look like this:

//print_r($_POST) gives:

Array
(
    [F1FirstName] => John
    [F2FirstName] => Jane
)

..the easiest thing to do is to loop through each of those with foreach:

foreach ($_POST as $key => $value) {
  // first $key will be "F1FirstName"
  // first $value will be "John"

  // second $key will be "F2FirstName"
  // second $value will be "Jane"

  // etc
}

Now, in that $_POST will also be other types of fields, like e.g. F1MobilePhone or whatever, that require different validations and different messages. So for each of those fields, you need to find out what type it is, to determine what kind of message to enter into your validation function. One option would be (this goes within the foreach statement):

if (strstr($key,'FirstName')) {
  // add a validation rule for the FirstName type
}
if (strstr($key,'Somethingelse')) {
  // etc
}

I don't know how your validation script works, but I'm guessing you're doing something like this:

// import the validation library
require("validation.php");

$rules = array(); // stores the validation rules

// All Enrollee Rules
$rules[] = "required,Num1FirstName,The First Name field is required.";

// Call on the validation function
$result = validate($rules);

Then you'll probably receive back whether, in this case, "Num1FirstName" was valid or not. Since you use an array $rules, the validator can probably handle multiple lines at once. Simply add more values to the array, but don't add another variable. If you do this:

$rules[] = "required,Num1FirstName,Num2FirstName,The First Name field is required.";

..the validator will think that the "Num2FirstName" is the error message, since that's the 3rd value you enter, and it won't know what to do with the actual message which is now 4th value. Try this instead:

$rules[] = "required,Num1FirstName,The First Name field is required.";
$rules[] = "required,Num2FirstName,The First Name field is required.";

So bringing that all together gives you this:

foreach ($_POST as $key => $value) {
  // first $key will be "F1FirstName"
  // first $value will be "John"

  // second $key will be "F2FirstName"
  // second $value will be "Jane"

  if (strstr($key,'FirstName')) {
    $rules[] = "required,$key,The First Name field is required.";
  }
  if (strstr($key,'Somethingelse')) {
    $rules[] = "required,$key,Some other message for this type of field.";
  }
}

// call on your validate function and feed it the $rules array you've created

Adding JavaScript to (pre-)validate is a whole different story. In the end you still need to validate it in PHP because, like you said, the JS check can easily be bypassed. So I guess fixing this first might be best.

Saturday, May 29, 2021
 
Juriy
answered 7 Months ago
59
<?php
session_start(); //allows use of session variables

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   if (!isset($_POST["first-name"])) {
     $firstNameErr = "First name is required";
   } else {
     $first_name = test_input($_POST["first-name"]);
   }

    if (!isset($_POST["last-name"])) {
     $lastNameErr = "Last name is required";
   } else {
     $last_name = test_input($_POST["last-name"]);
   }

   if (!isset($_POST["email"])) {
     $emailErr = "Email is required";
   } else {
     $email = test_input($_POST["email"]);
   }

   if (!isset($_POST["message"])) {
     $messageErr = "Message is required";
   } else {
     $message = test_input($_POST["message"]);
   }

   if(isset($first_name) && isset($last_name) && isset($email) && isset($message))
   {
     $_SESSION['first_name'] = $first_name;
     $_SESSION['last_name'] = $last_name;
     $_SESSION['email'] = $email;
     $_SESSION['message'] = $message;

     header("Location: php_mailer_form.php");
   }
}

function test_input($data) {
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}
?>



<form class="ui form"  method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
  <div class="field">
    <label>First Name</label>
    <input name="first-name" id="first-name" placeholder="First Name" type="text">
     <?php if(isset($firstNameErr)) print ('<span class="error">* ' . $firstNameErr . '</span>'); ?>
  </div>
  <div class="field">
    <label>Last Name</label>
    <input name="last-name" id="last-name" placeholder="Last Name" type="text">
     <?php if(isset($lastNameErr)) print ('<span class="error">* ' . $lastNameErr . '</span>'); ?>
  </div>
    <div class="field">
    <label>Email</label>
    <input name="email" id="email" placeholder="Email" type="email">
     <?php if(isset($emailErr)) print ('<span class="error">* ' . $emailErr . '</span>'); ?>
  </div>
  <div class="field">
    <label>Message</label>
    <textarea rows="2" placeholder="Please type in your message" name="message" id="message"></textarea>
     <?php if(isset($messageErr)) print ('<span class="error">* ' . $messageErr . '</span>'); ?>
  </div>

  <button class="ui button" type="submit">Submit</button>
</form>

Now in your other page, to access the variables, simply call "session_start();" at the top of the page as we did here, then use call "$_SESSION['message']" to get the value of message. Does this answer your question? Also note, I edited the html so that the error message div only prints if the error variable was set.

Saturday, May 29, 2021
 
inieto
answered 7 Months ago
17

Yes, you are not closing right your (neverending) last if, you have it ending like this:

... && strlen($valid_estimated_ship_date>0))

and it should be:

.. && (strlen($valid_estimated_ship_date)>0))
Saturday, May 29, 2021
 
pocketfullofcheese
answered 7 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share