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.


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) {
//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;}
        echo'<script type="text/javascript">alert("Enter your message.")</script>';
        return FALSE; }}

if (isset($_POST['submit'])) {

  $message = $_POST['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>';  }  }


If I understand your problem well, the problem is that you don't want an if clause to become too long and that you have a problem with empty parameters. Your way of checking seems right to me, for the other part I asked myself if you can't just add something like this to the functions namecheck() emailcheck() and messagecheck():

 if (strlen($fname) == 0 || strlen($lname) == 0) return false;

Furthermore in your code line with the checks you have two times the emailcheck instead of the messagecheck once:

  if (($namecheck === TRUE) && ($emailcheck ===TRUE) && ($emailcheck ===TRUE)) {

Good luck, hope it helped.



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy