I used this article on SitePoint as a reference ( https://www.sitepoint.com/form-validation-with-php ) and came up with the following. We are trying to move away from using jQuery for Form Validation since it can be turned off in the browser.
But, now I need to send the data to our normal PHP script that sends the email, does further validation, formatting and submitting into a CRM etc. Basically, if all the rules were passed, send the values from the form to our script for further processing.
This is the PHP written at the top of the file, it could be a little redundant but works:
<?php
// define variables and set to empty values
$fname = $lname = $address = $city = $state = $zip = $phone = $email = "";
$fname_error = $lname_error = $address_error = $city_error = $state_error = $zip_error = $phone_error = $email_error = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$fname_error = "required";
} else {
$fname = test_input($_POST["fname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
$fname_error = "Only letters and white space allowed";
}
}
if (empty($_POST["lname"])) {
$lname_error = "required";
} else {
$lname = test_input($_POST["lname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
$lname_error = "Only letters and white space allowed";
}
}
if (empty($_POST["address"])) {
$address_error = "required";
} else {
$address = test_input($_POST["address"]);
}
if (empty($_POST["city"])) {
$city_error = "required";
} else {
$city = test_input($_POST["city"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
$city_error = "Only letters and white space allowed";
}
}
if (empty($_POST["state"])) {
$state_error = "required";
} else {
$state = test_input($_POST["state"]);
}
if (empty($_POST["zip"])) {
$zip_error = "required";
} else {
$zip = test_input($_POST["zip"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[0-9]*$/",$zip)) {
$zip_error = "Only numbers allowed";
}
}
if (empty($_POST["phone"])) {
$phone_error = "required";
} else {
$phone = test_input($_POST["phone"]);
}
if (empty($_POST["email"])) {
$email_error = "required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
The form is using:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
I am a beginner with PHP and struggling to take what I have and submit the data into an external script for processing.