Jump to content

PHP code validatation


Go to solution Solved by kicken,

Recommended Posts

Hey!

So I've encountered some issues with my code. It validates the input. If the input is correct it writes to a file. If not - should display the error message with errors that should be fixed. But it does not display it. I've tried many things to fix it but it just does not work. It refreshes the page and that's all. Can somebody help me with it?

Thanks in advance!

<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="author" content="Nikita Z">
    <title>LAB 5 - PHP Form</title>
</head>
<body>
    <nav>
          <ul>
            <li><a href="index.php">Home</a></li>
            <li><a href="download.php">Download Data</a></li>
          </ul>
    </nav>
    <h1>Registration Form</h1>
    <form method="post" action="index.php" id="formReserve">
    <label for="nameFirst">First Name:</label>
    <input type="text" id="nameFirst" name="nameFirst" required><br><br>
    <label for="nameMiddle">Middle Name:</label>
    <input type="text" id="nameMiddle" name="nameMiddle"><br><br>
    <label for="nameLast">Last Name:</label>
    <input type="text" id="nameLast" name="nameLast" required><br><br>
    <label for="salutation">Salutation:</label>
    <select id="salutation" name="salutation" required>
        <option value="Mr.">Mr.</option>
        <option value="Ms.">Ms.</option>
        <option value="Mrs.">Mrs.</option>
        <option value="Sir">Sir</option>
        <option value="Prof.">Prof.</option>
        <option value="Dr.">Dr.</option>
    </select><br><br>
    <label for="age">Age:</label>
    <input type="number" id="age" name="age" required min="18" max="98"><br><br>
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required><br><br>
    <label for="phone">Phone(Including country code):</label>
    <input type="tel" id="phone" name="phone" required><br><br>
    <label for="dateArrive">Date of Arrival:</label>
    <input type="date" id="dateArrive" name="dateArrive" required><br><br>
    <input type="submit" id="submitReservation" name="submit" value="Submit">
</form>
<?php

//Set error reporting to all
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Define an array to store validation errors
    $errors = array();

// Check if the form has been submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

     // Validate first name
        if (isset($_POST['nameFirst']) && !preg_match('/^[a-zA-Z]+$/i', $_POST['nameFirst'])) {
            $errors[] = 'First name must not contain digits or special characters';
        }

        // Validate middle name
        if (isset($_POST['nameMiddle'])) {
    if ($_POST['nameMiddle'] === '') {
        // Middle name is empty
    } else if (!preg_match('/^[a-zA-Z]+$/i', $_POST['nameMiddle'])) {
        $errors[] = 'Middle name must not contain digits or special characters';
    }
}

        // Validate last name
        if (isset($_POST['nameLast']) && !preg_match('/^[a-zA-Z]+$/i', $_POST['nameLast'])) {
            $errors[] = 'Last name must not contain digits or special characters';
        }

    // Validate salutation
$allowedSalutations = array('Mr.', 'Ms.', 'Mrs.', 'Sir', 'Prof.', 'Dr.');
if (isset($_POST['salutation']) && !in_array($_POST['salutation'], $allowedSalutations)) {
    $errors[] = 'Invalid salutation';
}

    // Validate age
if (isset($_POST['age']) && ($_POST['age'] < 18 || $_POST['age'] > 98)) {
    $errors[] = 'Age must be between 18 and 98';
}

// Validate email
if (isset($_POST['email']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    $errors[] = 'Invalid email address';
}

// Validate phone number
if (isset($_POST['phone']) && !preg_match('/^(\+?\d{1,3}[\s-]?)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/', $_POST['phone'])) {
    $errors[] = 'Invalid phone number';
}

// Validate arrival date
if (isset($_POST['dateArrive'])) {
    $minDate = new DateTime('2023-01-01');
    $maxDate = new DateTime('2033-01-01');
    $arrivalDate = DateTime::createFromFormat('Y-m-d', $_POST['dateArrive']);
    if (!$arrivalDate || $arrivalDate < $minDate || $arrivalDate > $maxDate) {
        $errors[] = 'Invalid arrival date';
    }
}

// If there are no validation errors, store the form data
if (empty($errors)) {
// Define the name of the CSV file
$filename = 'data.csv';

// Define the data to be written to the CSV file
$data = array(
    $_POST['nameFirst'],
    $_POST['nameMiddle'],
    $_POST['nameLast'],
    $_POST['salutation'],
    $_POST['age'],
    $_POST['email'],
    $_POST['phone'],
    $_POST['dateArrive'],
);

// Convert the data array to a string
$data_string = implode(";", $data) . "\n";

// If the file exists, add the data to it or if no file, create it
if (file_exists($filename)) {
    $file = fopen($filename, 'a');
} else {
    $file = fopen($filename, 'w');
    // Write header row
    fwrite($file, "First Name;Middle Name;Last Name;Salutation;Age;Email;Phone;Date of Arrival\n");
}

// Write the data to the CSV file
fwrite($file, $data_string);

// Close the file handle
fclose($file);

// Display a success message
echo '<p><div id="confirmedText">Thank you for registering!</p>';
echo '<p>Registration details:</p>';
echo '<ul>';
echo '<li>Name: '.$_POST['salutation'].' '.$_POST['nameFirst'].' '.$_POST['nameMiddle'].' '.$_POST['nameLast'].'</li>';
echo '<li>Age: '.$_POST['age'].'</li>';
echo '<li>Email: '.$_POST['email'].'</li>';
echo '<li>Phone: '.$_POST['phone'].'</li>';
echo '<li>Date of Arrival: '.$_POST['dateArrive'].'</li>';
echo '</ul>';
 

// Add a "Download Registration Details" button
 
    echo '<form method="post" action="download.php">';
    echo '<input type="hidden" name="salutation" value="'.$_POST['salutation'].'">';
    echo '<input type="hidden" name="nameFirst" value="'.$_POST['nameFirst'].'">';
    echo '<input type="hidden" name="nameMiddle" value="'.$_POST['nameMiddle'].'">';
    echo '<input type="hidden" name="nameLast" value="'.$_POST['nameLast'].'">';
    echo '<input type="hidden" name="age" value="'.$_POST['age'].'">';
    echo '<input type="hidden" name="email" value="'.$_POST['email'].'">';
    echo '<input type="hidden" name="phone" value="'.$_POST['phone'].'">';
    echo '<input type="hidden" name="dateArrive" value="'.$_POST['dateArrive'].'">';
    echo '<button type="submit" name="submit">Download Registration Details</button>';
    echo '</form>';
}
}


else {
// If there are validation errors, display them to the user
echo '<div id="confirmedError">';
echo '<p>Please fix the following errors:</p>';
echo '<ul>';
foreach ($errors as $error) {
echo '<li>' . $error . '</li>';
}
echo '</ul>';
}



?>

</body>
</html>

 

Link to comment
https://forums.phpfreaks.com/topic/316005-php-code-validatation/
Share on other sites

I'm asking a stupid question but way are you validating a person name? The Late Prince would had have trouble with that. 🤣  The person's age is another head scratcher. If some of that information is not right simply have it where a person can edit the information, have it idiot proof like the person's age as an example or have a confirmation page.

Edited by Strider64
  • Haha 1
4 minutes ago, Strider64 said:

I'm asking a stupid question but way are you validating a person name? The Late Prince would had have trouble with that. 🤣  The person's age is another head scratcher. If some of that information is not right simply have it where a person can edit the information, have it idiot proof like the person's age as an example or have a confirmation page.

Well of course I would validate names and age in a different way, but we have strict lab specifications where all the validation thing must be same as in specification 😂

 

  • Solution

You have your if structure's out of order.  This is the structure you currently have:

if ($_SERVER['REQUEST_METHOD'] === 'POST'){
    //validate data
    if (empty($errors)){
        //save file
    }
} else {
    //Display errors
}

You are only trying to display the errors when it's a GET request, which won't be running any of the validations and thus never generate any errors.

The code to display your errors should be the else branch of your empty($errors) check instead.

4 minutes ago, kicken said:

You have your if structure's out of order.  This is the structure you currently have:

if ($_SERVER['REQUEST_METHOD'] === 'POST'){
    //validate data
    if (empty($errors)){
        //save file
    }
} else {
    //Display errors
}

You are only trying to display the errors when it's a GET request, which won't be running any of the validations and thus never generate any errors.

The code to display your errors should be the else branch of your empty($errors) check instead.

Thank you, that worked!

  • 2 months later...

I reviewed your code, and it seems that the issue lies in the conditional logic for displaying validation errors. In your code, the validation errors are displayed within the else block of the main if ($_SERVER['REQUEST_METHOD'] === 'POST') condition. However, this else block only executes when the form is not submitted or when there are validation errors.

To fix the issue and ensure that the validation errors are displayed correctly, you can move the error display code outside of the else block and place it after the HTML form. Here's the modified code:

<?php
// ... Your existing code ...

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // ... Your existing validation code ...
    
    // If there are no validation errors, store the form data
    if (empty($errors)) {
        // ... Your existing code ...
    }
}

// Display validation errors if any
if (!empty($errors)) {
    echo '<div id="confirmedError">';
    echo '<p>Please fix the following errors:</p>';
    echo '<ul>';
    foreach ($errors as $error) {
        echo '<li>' . $error . '</li>';
    }
    echo '</ul>';
    echo '</div>';
}
?>

By moving the error display code outside the else block, it will be executed regardless of whether the form was submitted or not. This way, when there are validation errors, they will be displayed correctly below the form.

Make sure to place the modified code in the appropriate location within your file, following the HTML form

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.