I am using if
statements within my functions to validate form fields and then on the isset
event.
I want to be able to create many different functions to validate various fields groups, and it seems that this statement could grow very long:
if (($namecheck === TRUE) && ($emailcheck ===TRUE) && ($messagecheck ===TRUE)) {
This also causes the alert for each function if no data is entered. I can circumvent this by making statements if one proves false, then stop, but it is only getting messier and messier.
I don't need my code written for me. As such, I am interested in what you suggest, in terms of if
statements, using switch
or loop instead, or any other ideas.
I am not so much wanting a solution here, as reasons for why some ways are better than others. For the purposes of this discussion, I am not concerned with client side validation. It is a focus on PHP functions only.
<?php
include ("contact.html");
function namecheck ($fname, $lname) {
$regexp ="/^[A-Za-z]+$/";
//filter through names
if (preg_match($regexp,$fname,$lname)) {
return TRUE; }
else {
echo'<script type="text/javascript">alert("Enter your names.")</script>';
return FALSE; }}
function emailcheck ($email1, $email2) {
$regexp="/^[a-zA-A-Z0-9_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9.-]+$/";
//validate email address
if (preg_match($regexp,$email1,$email2)) {
return TRUE; }
else {
echo '<script type="text/javascript">alert ("Enter a valid email address.")</script>';
return FALSE; }}
function messagecheck ($message) {
$regex = "/^[a-zA-Z0-9.?!_-]+$/";
//validate message text
if (preg_match($regex,$message)) {
return TRUE;}
else{
echo'<script type="text/javascript">alert("Enter your message.")</script>';
return FALSE; }}
if (isset($_POST['submit'])) {
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$namecheck=namecheck($fname);
$email1=$_POST['email1'];
$email2=$_POST['email2'];
$emailcheck=emailcheck($email1,$email2);
$message = $_POST['message'];
$messagecheck=messagecheck($message);
if (($namecheck === TRUE) && ($emailcheck ===TRUE) && ($emailcheck ===TRUE)) {
$subject="website contact";
mail("myemail", $subject ,$message , "From: $email1");
echo '<script type="text/javascript"> alert("Your form has been submitted.") </script>'; } }
?>