Have an account? Sign in
Login  Register  Facebook
How to validate email address
Hi,

I wanted to know how I can get the email to validate

My code is


if ($_POST) {

	$expected = array('name', 'email', 'emailmessage');
	$validation = array(
		'name'		=> 'Please provide your full name',
		'email'		=> 'Please provide your valid email address',
		'emailmessage'	=> 'Please provide message'
	);
	
	$errors = array();
	$output = array();

	foreach($expected as $key) {
		
		$input = htmlspecialchars($_POST[$key]);
	
		if (array_key_exists($key, $_POST)) {
			if (empty($_POST[$key])) {
				$errors[$key] = $validation[$key];
			} else {
				$output[$key] = $_POST[$key];
			}
		} else {
			$errors[$key] = $validation[$key];
		}
	
	}

	if (!empty($errors)) {
		$array = array('error' => true, 'fields' => $errors);
	} else {
	
		// PROCESS FORM
		
	// ---------------------------------------------------------
	// BEGIN EDITING
	// ---------------------------------------------------------

	$to = "[email protected]"; //This is the email address messages will be sent to
	$web_name = "My Test Web Form"; //This is the name of your website that will show in your email inbox
	
	//get IP address
	$ip = $_SERVER['REMOTE_ADDR'];

	//make time
	$time = time();
	$date = date("r", $time);

	// ---------------------------------------------------------
	// END EDITING
	// ---------------------------------------------------------
	
	$emailmessage = trim($emailmessage);
	$emailmessage = nl2br($emailmessage);
	$emailmessage = htmlspecialchars($emailmessage);
	$emailmessage = wordwrap($emailmessage, 70);

	//Visible form elements
	$name = $_POST['name']; //Sender's name
	$email = $_POST['email']; //Sender's email
	$emailmessage = htmlspecialchars($_POST['emailmessage']); //Sender's message
	
	//Setting up email
	$subject = "New Message from $web_name";
	
	$message = "
				New message from $name <br/><br/>
				
				Message:<br />
				$emailmessage
				<br/>
				
				<br/>
				Email: $email<br />
				IP:</strong> <span style=\"color:#990000;\">$ip</span><br />
				Date:</strong> $date
				
				";
	
	$header  = 'MIME-Version: 1.0' . "\r\n";
	$header .= 'Content-type: text/html; charset=utf-8' . "\r\n";
	$header .= 'From:'. $email . " \r\n";
				
	$sent = mail($to, $subject, $message, $header);
	
		//$message = '<div id=message>You have successfully subscribed to our newsletter</div>';
		$array = array('error' => false, 'message' => $message);
	}
		
	echo json_encode($array);
}

I want the errors passed through the array but I have the below code and I do not know how to call it to validate the email and pass the error in the $validation array

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {

	// email is valid
	
} else {

	// email is invalid
	
}


All help is much apprecaited.

Thanks

Kind Regards
Started: October 20, 2011 Latest Activity: October 23, 2011 php java
3 Answers
read and try to understand this code
$field_rules = array(
    'name' => 'required',
    'email' => 'required|valid_email',
    'phone' => '',
    'contact_reason' => 'required',
    'message' => 'required'
);


$error_messages = array(
    'required' => 'This field is required',
    'valid_email' => 'Please enter a valid email address'
);


$error_list = '';


$fields = $_POST;



if (!empty($fields))
{
    //Validate each of the fields
    foreach ($field_rules as $field => $rules)
    {
        $rules = explode('|', $rules);

        foreach ($rules as $rule)
        {
            $result = null;

            if (isset($fields[$field]))
            {
                if (!empty($rule))
                    $result = $rule($fields[$field]);

                if ($result === false)
                {
                    $field_name = ucwords(implode(' ', explode('_', $field)));

                    $error_list .= "<div class='error'>$field_name: " . $error_messages[$rule] . "</div>";
                }
            }
        }
    }

    if (empty($error_list))
    {
        $subject = '[Contact Form] New message from ' . $fields['name'] . '.';

        $content = $fields['name'] . " sent you a message from your contact form:rnn";
        $content .= "-------n" . $fields['message'] . "rnn";
        $content .= "Contact Reason: " . $fields['contact_reason']
                . " nnEmail: " . $fields['email']
                . " nnPhone: " . $fields['phone'] . " nn";

        if (mail($email_address, $subject, $content, "From: " . $fields['email'] . "rnReply-To: " . $fields['email'] . "rnReturn-Path: " . $fields['email'] . "rn"))
        {

            echo "<h2 class='success'>Message Sent</h2>";
            echo "<br/><p class='success'>Thank you <strong>" . $fields['name'] . "</strong>, your message has been submitted and someone will contact you shortly.</p>";
        }
        else
        {

            echo 'ERROR!';
        }
    }
}


function valid_email($str)
{
    return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $str) ? false : true;
}

Posted: MacOS
In: October 23, 2011

Edited: MacOS
In: October 23, 2011

<?php
# Validation Class
# www.C0derz.com
# GPL License 
class Validation 
{
	public static function Is_alpha($string,$min,$max)
	{
		if(!Validation::Length($string,$min,$max)){return false;}
		else return (bool) eregi("^[a-zA-Z]+$",$string); 
	}
	public static function Length($string,$min,$max)
	{
		if(empty($min) && empty($max)) {return true;}
		if(empty($min) && !empty($max)){if(strlen($string) < $max){return true;}}
		else if(!empty($min) && empty($max)){if(strlen($string) > $min){return true;}}
		else if(strlen($string) > $min && strlen($string) < $max){return true;}else{return false;}
	}
	public static function Is_Email($string,$min,$max)
	{
		if(!Validation::Length($string,$min,$max)){return false;}
		else return (bool) filter_var($string, FILTER_VALIDATE_EMAIL);
	}
	public static function Is_Mobile($string,$min,$max)
	{
		if(!Validation::Length($string,$min,$max)){return false;}
		else return (bool) eregi("^[0-9]{8,20}$",$string);
	}	
	public static function Is_Phone($string,$min,$max)
	{
		if(!Validation::Length($string,$min,$max)){return false;}
		else return (bool) eregi("^[0-9 ]{7,13}$",$string);
	}
	public static function Is_Url($string,$min,$max)
	{
		if(!Validation::Length($string,$min,$max)){return false;}
		else return (bool) eregi("^(https?|ftp)\\:\\/\\/([a-z0-9+!*(),;?&=\$_.-]+(\\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?[a-z0-9+\$_-]+(\\.[a-z0-9+\$_-]+)*(\\:[0-9]{2,5})?(\\/([a-z0-9+\$_-]\\.?)+)*\\/?(\\?[a-z+&\$_.-][a-z0-9;:@/&%=+\$_.-]*)?(#[a-z_.-][a-z0-9+\$_.-]*)?\$", $string);
	}
	public static function Is_Ip4($string)
	{
		return (bool) preg_match("/^((\d{1,2}|[01]\d{2}|2([0-4]\d|5[0-5]))\.){3}(\d{1,2}|[01]\d{2}|2([0-4]\d|5[0-5]))$/",$string);
	}
	public static function Is_Ip6($string)
	{
		if(empty($string)){return false;}
	    // fast exit for localhost
	    if (strlen($string) < 3)
	        return $string == '::';
	
	    // Check if part is in IPv4 format
	    if (strpos($string, '.'))
	    {
	        $lastcolon = strrpos($string, ':');
	        if (!($lastcolon && Validation::Is_Ip4(substr($string, $lastcolon + 1))))
	            return false;
	
	        // replace IPv4 part with dummy
	        $string = substr($string, 0, $lastcolon) . ':0:0';
	    }
	
	    // check uncompressed
	    if (strpos($string, '::') === false)
	    {
	        return preg_match('/^(?:[a-f0-9]{1,4}:){7}[a-f0-9]{1,4}$/i', $string);
	    }
	
	    // check colon-count for compressed format
	    if (substr_count($string, ':') < 8)
	    {
	        return preg_match('/^(?::|(?:[a-f0-9]{1,4}:)+):(?:(?:[a-f0-9]{1,4}:)*[a-f0-9]{1,4})?$/i', $string);
	    }
		return false;
	}
}
?>

Posted: Nasser
In: October 21, 2011

@ NasserThank you for your reply but I am still none the wiser.I do not know how to call the funxtion inside my code to validate the email address.If you give me your email address I could email you the full files for you to have a look at please.Kind Regards
October 23, 2011

this is a class for "Validation"
October 23, 2011

it's totally easy .. use as the following <?php include("Validation.php"); $email = "[email protected]"; if(Validation::Is_Email($email)) { echo "true Email"; } else {echo "False !";} ?>
October 23, 2011

you can also determine the length of the email using the following Validation::Is_Email($email,5,20); the email between 5 and 20 chars
October 23, 2011

@Nasser, this is very good class, but @qakbar5 problem is how to add any "Validation" on the code
October 23, 2011

include("Validation.php"); $email = $_POST['email']; //Sender's email if(Validation::Is_Email($email)) { echo "true Email"; } else {echo "False !";}
October 23, 2011

on his code :) ( in the first post )
October 23, 2011

heheheh ,, let him try and learn :P
October 23, 2011

hhhhhhhhh, ok but it think the 2nd code will do what he want
October 23, 2011

Try to replace the "foreach" to
    foreach($expected as $key) {
         
        $input = htmlspecialchars($_POST[$key]);
     
        if (array_key_exists($key, $_POST)) {
            if (empty($_POST[$key])) {
                $errors[$key] = $validation[$key];
            } else {
                if($key == 'email'){
                    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
                        $output[$key] = $_POST[$key];
                    }else{
                        $errors[$key] = 'NON VALIDATE_EMAIL'
                    }
                }else{
                   $output[$key] = $_POST[$key]; 
                }
            }
        } else {
            $errors[$key] = $validation[$key];
        }
     
    }

Posted: Dina
In: October 20, 2011

Hi Dina,Sorry but this did not work.My form uses Ajax and PHP.Would it help if I can email you the full files and you could have a look for me please.Regards
October 20, 2011

Your Answer

xDo you want to answer this question? Please login or create an account to post your answer