2082 12

CSC329 ยท 2082 ยท 5 marks

Create a PHP form with form elements. Write a program to perform form validation. Use your own assumptions for the validation.

Create a PHP form with form elements. Write a program to perform form validation. Use your own assumptions for the validation. [5]

Web TechnologyChapter 6: Server Side Scripting using PHPForm Validation

PHP Form with Validation

Assumptions for Validation:

  • Username: required, minimum 5 characters
  • Password: required, must start with a digit and end with $
  • Gender (radio button): must be selected
  • Hobbies (checkbox): at least one must be checked

Complete PHP Program

<?php
// Initialize variables
$username = $password = $gender = "";
$hobbies = [];
$errors = [];
$success = "";

// Process form on submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Username Validation
    if (empty($_POST["username"])) {
        $errors[] = "Username is required.";
    } else {
        $username = trim($_POST["username"]);
        if (strlen($username) < 5) {
            $errors[] = "Username must be at least 5 characters long.";
        }
    }

    // Password Validation
    if (empty($_POST["password"])) {
        $errors[] = "Password is required.";
    } else {
        $password = trim($_POST["password"]);
        // Must start with a digit and end with $
        if (!preg_match('/^\d/', $password) || !preg_match('/\$$/', $password)) {
            $errors[] = "Password must start with a digit and end with '$'.";
        }
    }

    // Gender Validation (Radio Button)
    if (empty($_POST["gender"])) {
        $errors[] = "Please select your gender.";
    } else {
        $gender = $_POST["gender"];
    }

    // Hobbies Validation (Checkbox)
    if (empty($_POST["hobbies"])) {
        $errors[] = "Please select at least one hobby.";
    } else {
        $hobbies = $_POST["hobbies"];
    }

    // If no errors, show success
    if (empty($errors)) {
        $success = "Form submitted successfully! Welcome, " . htmlspecialchars($username) . ".";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>PHP Form Validation</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 30px; }
        .error { color: red; }
        .success { color: green; font-weight: bold; }
        label { display: inline-block; width: 120px; }
        input[type="text"], input[type="password"] {
            padding: 5px;
            width: 200px;
        }
        .form-group { margin: 10px 0; }
    </style>
</head>
<body>

<h2>Registration Form</h2>

<!-- Display Errors -->
<?php if (!empty($errors)): ?>
    <ul class="error">
        <?php foreach ($errors as $error): ?>
            <li><?php echo $error; ?></li>
        <?php endforeach; ?>
    </ul>
<?php endif; ?>

<!-- Display Success -->
<?php if (!empty($success)): ?>
    <p class="success"><?php echo $success; ?></p>
<?php endif; ?>

<!-- HTML Form -->
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">

    <!-- Username -->
    <div class="form-group">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username"
               value="<?php echo htmlspecialchars($username); ?>">
    </div>

    <!-- Password -->
    <div class="form-group">
        <label for="password">Password:</label>
        <input type="password" id="password" name="password">
    </div>

    <!-- Gender (Radio Buttons) -->
    <div class="form-group">
        <label>Gender:</label>
        <input type="radio" name="gender" value="Male"
            <?php echo ($gender == "Male") ? "checked" : ""; ?>> Male
        <input type="radio" name="gender" value="Female"
            <?php echo ($gender == "Female") ? "checked" : ""; ?>> Female
        <input type="radio" name="gender" value="Other"
            <?php echo ($gender == "Other") ? "checked" : ""; ?>> Other
    </div>

    <!-- Hobbies (Checkboxes) -->
    <div class="form-group">
        <label>Hobbies:</label>
        <input type="checkbox" name="hobbies[]" value="Reading"
            <?php echo (in_array("Reading", $hobbies)) ? "checked" : ""; ?>> Reading
        <input type="checkbox" name="hobbies[]" value="Gaming"
            <?php echo (in_array("Gaming", $hobbies)) ? "checked" : ""; ?>> Gaming
        <input type="checkbox" name="hobbies[]" value="Coding"
            <?php echo (in_array("Coding", $hobbies)) ? "checked" : ""; ?>> Coding
        <input type="checkbox" name="hobbies[]" value="Travelling"
            <?php echo (in_array("Travelling", $hobbies)) ? "checked" : ""; ?>> Travelling
    </div>

    <!-- Submit Button -->
    <div class="form-group">
        <input type="submit" value="Register">
    </div>

</form>

</body>
</html>

Key Points Explained

ElementValidation Rule
usernameRequired, length >= 5
passwordRequired, starts with digit, ends with $
genderRadio button must be selected
hobbies[]At least one checkbox must be checked
  • $_SERVER["REQUEST_METHOD"] == "POST" checks if the form is submitted.
  • preg_match() is used for pattern-based password validation.
  • htmlspecialchars() prevents XSS attacks on output.
  • empty($errors)

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.