Jump to content

Email validation


KJ

Recommended Posts

Whilst recently amending our sites mail form PHP file, to replace the ‘ereg’ string associated to the ‘Telephone’ input box, with the ‘preg_match’ string, I noticed that our ‘Email’ input box also uses the ‘ereg’ string.

Killersites member Wickham pointed out, whilst advising me on my Numerical validation topic, that the ‘ereg’ string was to be obsolete in future PHP versions so I thought I’d best have a go at replacing this string too.

I’ve spent a good few hours trying to get a new string to work, sadly I have failed.

 

Here’s the old ‘ereg’ string that has worked successfully for many years;

 

if (!ereg("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a- z]{2,6})$" , strtolower($_POST['email']))) {

exit("<p>Sorry!! That is not a valid e-mail address, please use another.</p>");

}

 

Here’s the most successful ‘preg_match’ string I've managed to achieve;

 

if (preg_match(“/^([a-z0-9])+([a-z0-9\._-]+)*@([a-z0-9_-])+([a-z0-9\._-]{2,6})/” , ($_POST['email']))) {

exit ("<p>Sorry!! That is not a valid email address, please use another.</p>");

}

 

It will email addresses that do NOT have the @ within them, myselfmysite.com or myself_mysite.co.uk work fine, but myself@mysite.com or my_self@mysite.co.uk do not.

 

I tried single quote as apposed to double, removing the brackets and the parenthesising [^], they all fail with parsing errors.

Also, am I correct in excluding uppercase letters within the criteria?

 

Any help much appreciated!!!!!!!

Link to comment
Share on other sites

Hello!

 

Sorry I don't really understand your situation, however here is a Javascript function I implement to check the email of the user.

 

<script type="text/javascript">

/***********************************************
* No need to edit this function. The only thing you will need to edit is the submit button.
* Example <input type="submit" name="submit" onclick="return checkmail([color="#FF0000"]this.form.myemail[/color])" value="Sign Up" />
* In the example above, you would have to change the argument (this.form.myemai) to match where your input box is located.
* So you may use something like this
*<input type="submit" name="submit" onclick="return checkmail(this.[color="#FF0000"]FORMNAME.INPUTNAME[/color])" value="Sign Up" />
***********************************************/

var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i

function checkmail(e){
var returnval=emailfilter.test(e.value)
if (returnval==false){
alert("Please enter a valid email address.")
e.select()
}
return returnval
}

</script>

 

So your complete [simple] document may look like this:

 

<html>
<head>
<title>SIMPLE DOCUMENT - Check email</title>

<script type="text/javascript">

var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i //Declare global var to check against

function checkmail(e) //Call this function when validating an email
{
var returnval=emailfilter.test(e.value)
if (returnval==false){
alert("Please enter a valid email address.")
e.select()
}
return returnval
}

</script>

</head>
<body>

<form name="form1" action="process.php" method="post">
Email: <input type="text" name="email1" value="someone@somewhere.com" /> <br />
<input type="submit" value="Check email" onclick="return checkmail(this.form1.email1)" /> /* When clicked - the value of email1 will be compared to the vairable - if it all checks out, the email was fine. */
</form>
</body>
</html>

Link to comment
Share on other sites

I also don't understand all the code, but this is the PHP email validation code that I use (JFab's code is javascript):-

if
(!preg_match("/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i",$email)) {
header( "Location: $errorurl" );

 

The main difference seems to be that my code has ! for NOT in front of preg_match while your's doesn't. Note that your original code had if (!ereg() which has ! in front of ereg. Both have the ^ in the code. I found that ^ is defined as

$a ^ $b Xor (exclusive or) Bits that are set in $a or $b but not both are set.

here http://www.php.net/manual/en/language.operators.bitwise.php

so the ^ is not strictly a NOT as I assumed before, but "not both"

and I think the ._%- or .- mean opposite or negative so [A-Z0-9._%-] means if not A-Z or 0-9 it is true.

 

I think what the code is doing is saying "if the preg_match as a whole is not true, show the error message" and the code inside the preg_match is saying "if it's not using characters which are not A-Z or numbers which are not 0-9 in all sequences, it is true". That doesn't make sense to me so I still can't get my head round the two NOTs.

 

Additionally, my code has [A-Z]{2,4} where your's has [A-Z]{2,6} and I think this is to limit the number of characters for the domain extension which used to be max four like .info but now there are longer extensions so I should probably increase my code to 6 (if that's what it's for).

Edited by Wickham
Link to comment
Share on other sites

Honestly, I wouldn't re-invent the wheel on this one. There are far too many edge cases to consider. There's a PHP class designed to validate email addresses here:

 

http://code.google.com/p/php-email-address-validation/

 

And using it is as simple as:

 

include('EmailAddressValidator.php');
$validator = new EmailAddressValidator;
if ($validator->check_email_address('test@example.org')) { 
   // Email address is technically valid 
} else {
   // Email not valid
}

Link to comment
Share on other sites

I also don't understand all the code, but this is the PHP email validation code that I use (JFab's code is javascript):-

if
(!preg_match("/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i",$email)) {
header( "Location: $errorurl" );

 

The main difference seems to be that my code has ! for NOT in front of preg_match while your's doesn't. Note that your original code had if (!ereg() which has ! in front of ereg. Both have the ^ in the code. I found that ^ is defined as

 

here http://www.php.net/manual/en/language.operators.bitwise.php

so the ^ is not strictly a NOT as I assumed before, but "not both"

and I think the ._%- or .- mean opposite or negative so [A-Z0-9._%-] means if not A-Z or 0-9 it is true.

 

I think what the code is doing is saying "if the preg_match as a whole is not true, show the error message" and the code inside the preg_match is saying "if it's not using characters which are not A-Z or numbers which are not 0-9 in all sequences, it is true". That doesn't make sense to me so I still can't get my head round the two NOTs.

 

Additionally, my code has [A-Z]{2,4} where your's has [A-Z]{2,6} and I think this is to limit the number of characters for the domain extension which used to be max four like .info but now there are longer extensions so I should probably increase my code to 6 (if that's what it's for).

 

I tried Wickhams code, which would not work within my PHP file, but after some juggling I did get a successful operation together.

Looks like this;

if (!preg_match("/^([a-z0-9])+([a-z0-9\._%-]+)*@([a-z0-9_-])+([a-z0-9\._-]{2,6})$/i" , ($_POST['email']))) {
exit ("<p>Sorry!! That is not a valid email address, please use another.</p>"); }

I too was puzzled by the apparent double negative, so I dug out some old university papers, I never wrote a line of PHP at uni but we did cover it a little and I remembered I still had the papers.

It appears that in this case, the forward slashes set out the actual search pattern (as usual) and the caret and dollar anchor the search pattern in a 'must match' manner. Effectively, a valid email address must match the entire pattern of the classes

In my code, the 1st set of characters must match one of ([a-z0-9]) and if applicable the 2nd set of characters must match one of ([a-z0-9\._%-]+) etc etc.

Of course I'm open to correction, if anyone knows or surmises better let us know.

Link to comment
Share on other sites

Hello!

 

Sorry I don't really understand your situation, however here is a Javascript function I implement to check the email of the user.

 

<script type="text/javascript">

/***********************************************
* No need to edit this function. The only thing you will need to edit is the submit button.
* Example <input type="submit" name="submit" onclick="return checkmail([color="#FF0000"]this.form.myemail[/color])" value="Sign Up" />
* In the example above, you would have to change the argument (this.form.myemai) to match where your input box is located.
* So you may use something like this
*<input type="submit" name="submit" onclick="return checkmail(this.[color="#FF0000"]FORMNAME.INPUTNAME[/color])" value="Sign Up" />
***********************************************/

var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i

function checkmail(e){
var returnval=emailfilter.test(e.value)
if (returnval==false){
alert("Please enter a valid email address.")
e.select()
}
return returnval
}

</script>

 

So your complete [simple] document may look like this:

 

<html>
<head>
<title>SIMPLE DOCUMENT - Check email</title>

<script type="text/javascript">

var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i //Declare global var to check against

function checkmail(e) //Call this function when validating an email
{
var returnval=emailfilter.test(e.value)
if (returnval==false){
alert("Please enter a valid email address.")
e.select()
}
return returnval
}

</script>

</head>
<body>

<form name="form1" action="process.php" method="post">
Email: <input type="text" name="email1" value="someone@somewhere.com" /> <br />
<input type="submit" value="Check email" onclick="return checkmail(this.form1.email1)" /> /* When clicked - the value of email1 will be compared to the vairable - if it all checks out, the email was fine. */
</form>
</body>
</html>

 

Thanks for the response JFab, I'm going to stick with the PHP for now, but I'll certainly look into the Javascript aspect, I'm all for education and self advancement.

Though it did take me a week to put together a Javascript picture gallery for a friends motorcycle website.

Link to comment
Share on other sites

Honestly, I wouldn't re-invent the wheel on this one. There are far too many edge cases to consider. There's a PHP class designed to validate email addresses here:

 

http://code.google.com/p/php-email-address-validation/

 

And using it is as simple as:

 

include('EmailAddressValidator.php');
$validator = new EmailAddressValidator;
if ($validator->check_email_address('test@example.org')) { 
   // Email address is technically valid 
} else {
   // Email not valid
}

 

Thank you monkeysaurus, another URL to add to my educational favourites.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...