How to add email validation

I would like to add email validation to my current email form but I just don’t know how I have found the right code to use but unsure where to place it.

<html>
<h1>contact us</h1> 

<?php

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

	//get form data
	$to = "devingeesr@gmail.com";
	$subject = "Form test";
	$name = $_POST['name'];
	$email = $_POST['email'];
	$message = $_POST['message'];
	
	$body = "From: $name\
 E-Mail: $email\
 Message:\
 $message";

	$errorstring = ''; //default value of error string
	
	
	echo "Invalid email";

	if (!$name)
		$errorstring = $errorstring."Name<br>";

	if (!$email)
		$errorstring = $errorstring."Email<br>";	

	if (!$message)
		$errorstring = $errorstring."Message<br>";
	
	if ($errorstring!="")
	
		echo "please fill out the following fields:<br>$errorstring";
		
	else {
	
		//run code
		
		echo "Your email has been submitted to Federalview.org. We will resopned as soon as possable.  Thank you for your time!";
		
		mail($to, $subject, $body);
		
		echo '<br><a href="javascript:window.close()">CLOSE WINDOW</a>'; 
	}
}	
	
?>

<p>
<form  action='conf_contact.php' method='POST'>
Name:<br>   
<input type='text' name='name' value='<?php echo $name; ?>'><br>
Email:<br>
<input type='text' name='email'value='<?php echo $email; ?>'><br>
Message: <br>
<textarea rows='15'  cols='40' name='message' ><?php echo $message; ?></textarea>
<p>
   <input type='submit' value='Send' name='submit'>
</form>

</html>

You will want to test the email matches a regular expression, to prove the email address is in the correct format.

A quick google will lead you to lots of various regexp’s that will do the job - some will be more limiting than others.

Another way is to use:


$_POST['email'] = 'bob@example.com';
var_dump(filter_var(, FILTER_VALIDATE_EMAIL));

PHP5 or greater.

[fphp]filter_var[/fphp]