Question: I've been looking around for ages and haven't found an easy way of editing this code so that when the user hasn't typed anything into a required field (all of the fields are required) an alert is shown asking the user to please enter something.

Can anyone help?

```
<?php
    $field_name = $_POST['name'];
    $field_email = $_POST['email'];
    $field_message = $_POST['message'];

    $mail_to = 'you@yourdomain.com';
    $subject = 'Site Mail';

    $body_message = 'From: '.$field_name."\n";
    $body_message .= 'Email: '.$field_email."\n";
    $body_message .= 'Message: '.$field_message;

    $headers = 'From: '.$field_email."\r\n";
    $headers .= 'Reply-To: '.$field_email."\r\n";

    $mail_status = mail($mail_to, $subject, $body_message, $headers);

    if ($mail_status) { ?>
        <script language="javascript" type="text/javascript">
            alert('Thanks! Your email has been sent.');
            window.location = 'index.html';
        </script>
    <?php
    }
    else { ?>
        <script language="javascript" type="text/javascript">
            alert('Sorry, something went wrong.');
            window.location = 'index.html';
        </script>
    <?php
    }
?>

```

Answer: 
You can use [**required**](https://www.google.com.ph/search?q=html5%20required&oq=html5%20re&aqs=chrome.4.69i57j69i60l2j0l3.3450j0&sourceid=chrome&ie=UTF-8#bav=on.2,or.r_qf.&fp=a91aea830d00bed6&q=html5%20required%20input) attribute if you want to take advantage of `html5` features.

Try this **[LINK](http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_input_required)**. It shows a simple demo of how to use the `required` attribute.
**[This](http://www.wufoo.com/html5/attributes/09-required.html)** one too
**PHP**

```
<?php
$fields = array([0]=>$field_name,[1]=>$field_email,[2]=>$field_message);
foreach($fields as $field){
    if !$field{
        echo "Please enter a value.";
    }
}
?>

```

Alternatively, you could use javascript validation, that would look something like this:

```
<script>
function formValid(){
  var valid = true;
  var fields = getElementByTag(input);
  for (var i;i>=fields.length;i++){
    if (!fields[i]){
      getElementById('warning').style.display='inline'; // assuming the error message element is called 'warning'
      getElementById('valid').value=1; // assuming we have an input that will indicate to the php code whether the form is validated  
    }
  }
}
</script>

```

for this script we would then add to the beginning of the form-action php block:

```
if(isset($_POST['submit'])&&$_POST['valid']!=1){
// form action code goes here
}

```