在PHP中验证联系表单

I have a contact form which I need validating in PHP to check if each field is correctly filled.

Here is what I have:

//Post fields
<?php
$field_name = $_POST['name'];
$field_email = $_POST['email'];
$field_services = $_POST['services'];
$field_it = $_POST['it'];
$field_location = $_POST['location'];
$field_message = $_POST['message'];


//mail_to omitted 


//Validation of contact form

$errormessage = '';
if($field_name == ''){

$errormessage += 'You have not entered your Name
';
}

if($field_email == ''){

$errormessage += 'You have not entered your Email Address
';
}

if($field_services == ''){

$errormessage += 'You have not chosen the service you require
';
}

if($field_it == ''){

$errormessage += 'You have not chosen the Date of your event
';
}

if($field_location == ''){

$errormessage += 'You have not entered the location of your event
';
}


if($errormessage != ''){ ?>

<script language="javascript" type="text/javascript">
    alert('The following fields have not neen entered correctly
<?php echo "$errormessage" ?>');
    window.location = 'contact.html';
</script>
<?php } 



if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
    alert('Thank you for the message. We will contact you shortly.');
    window.location = 'contact.html';
</script>
<?php
}


else { ?>
<script language="javascript" type="text/javascript">
    alert('Message failed. Please, send an email to s_ejaz@live.co.uk');
    window.location = 'contact.html';
</script>
<?php
}
?>

This does nothing when I try to submit an empty contact form, it should alert the user of the particular fields which were not filled but it doesn't. It just takes me to a blank white page.

Could anyone help me find where I am going wrong?

You should use strlen() and isset() to check if any data was received from the form.

Example:

if(!isset($_POST['name']) || strlen($_POST['name']) < 1){
    $errormessage .= 'You have not entered your Name
';
}

Instead of comparing variable to empty string like this $field_services == '' , use empty() or isset()

if(!empty($field_services)) or if(isset($field_services))

An other problem is that you concatenate strings using + , this is true if you are using javascript ,java or C# etc.. not PHP.

To concatenate variables using PHP:

 $var='Hello';
 $var.=' World !'

 echo $var;// Hello World !

So your code should be :

 if(empty($_POST['name'])){
   $errormessage .= 'You have not entered your Name
';
}

Try to use $errormessage.='Some text '; instead of $errormessage+='Some text ';.
Using "+" instead of ".", PHP treats the variable $errormessageas a number, and the assertion failed.

Also, you can use trim function to delete any space.

trim($_POST['name'])...