Jump to content

Very simple email validation (+ mysql_real_escape_string)


tomhoad

Recommended Posts

Hi there

 

I am using this function to do a very simple email validation:

 

function checkEmail($email) 
		{
		   if(eregi("^[a-zA-Z0-9_]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$]", $email)) 
		   {
			  return FALSE;
		   }
		}

            $email   = mysql_real_escape_string($_POST['email']);

		if(checkEmail($email) == FALSE) 
		{
		   echo "<p class=\"thankyou\">E-mail entered is not valid</p>";
		} 
		else 
		{
		    $comp_name = "Great competition!";
			$query = " INSERT INTO comps (email, comp_name) ". 
			" VALUES ('$email','$comp_name')"; 
			mysql_query($query) or die('Error ,query failed');
			echo "<p class=\"thankyou\">Thanks for entering!</p>";
		}

 

However, it always returns FALSE, even if it's a valid email. I think it's the way I'm suign mysql real escape string with it. Can anyone point me in the right direction?

Would it not be easier to use javascript. Im new to all of this but i have used some email validation in my script. The javascript code is as follows.

 

 

<script type="text/javascript">

var msg = '';

function validate_form()
{
	valid = true;

                if(checkEmail(document.enrolment.email.value) == false)

	{
		msg=msg+"Email address is not valid.\n";
		valid = false;
	}

if(msg=="" && valid ==true)
	{
		MM_popupMsg('Registration Complete!')
		register.submit();
	}

	else
	{
		msg = "You have the following errors which must be corrected to enrol: \n" + msg;
		alert (msg);
		//Initialise variable
		msg = '';
	}
	return valid;
}

//Display Message Registration complete
function MM_popupMsg(msg) 
{ 
  alert(msg);
}

//Check that email address is a valid format
function checkEmail(toCheck) 
{
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(toCheck))
	{
		return (true)
	}
	return (false)
}

 

 

Hope this is of some help

 

 

This should work :

 

<?php

$email = "[email protected]";

if (!eregi("^[a-z0-9\-\_\.\%\+]+@[a-z0-9\-\_]+\.[a-z]+$", $email))
{
echo "Invalid Email! ".$email;
} else {
echo "Valid Email! ".$email;
}

?>

 

However it won't work for email address using IP address instead of a domain name. It may return some false positive and probably need to be better tested before use.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.