Php Form Validation Tutorial Simple Part 3

Опубликовано: 28 Сентябрь 2024
на канале: Bassonia Tv
4
0

Php Form Validation Tutorial Simple Part 3
Certainly! Here's a simple tutorial on PHP form validation:

PHP Form Validation Tutorial - Part 1: Basic Setup

In this tutorial, we'll learn how to perform basic form validation using PHP. Form validation ensures that user-submitted data is accurate and properly formatted before processing.

Step 1: Create the HTML Form

html

!DOCTYPE html
html
head
titleSimple Form Validation/title
/head
body
h2Contact Us/h2
form method="post" action="process.php"
label for="name"Name:/label
input type="text" name="name" required
br
label for="email"Email:/label
input type="email" name="email" required
br
label for="message"Message:/label
textarea name="message" required/textarea
br
input type="submit" value="Submit"
/form
/body
/html

Step 2: Create the PHP Validation Script (process.php)

php

?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];

$errors = [];

// Validate Name
if (empty($name)) {
$errors[] = "Name is required";
}

// Validate Email
if (empty($email)) {
$errors[] = "Email is required";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format";
}

// Validate Message
if (empty($message)) {
$errors[] = "Message is required";
}

// Display Errors or Process Data
if (empty($errors)) {
// Process the form data (e.g., send email, save to database)
echo "Form submitted successfully!";
} else {
foreach ($errors as $error) {
echo $error . "br";
}
}
}
?

Explanation:

We create an HTML form that collects user information (name, email, message) and submits it to process.php for validation and processing.

In process.php, we use PHP to validate each form field. We check for empty values and use FILTER_VALIDATE_EMAIL to validate the email format.

If there are no validation errors, the form data can be processed (e.g., saved to a database or sent via email). Otherwise, the errors are displayed to the user.

Conclusion:

This is a basic introduction to PHP form validation. In the next part of the tutorial, we can expand on this by adding more advanced validation, handling different types of form fields, and enhancing the user experience. Form validation is an essential step to ensure the integrity and accuracy of user-submitted data.