0

i have been thnking about some validation of email using javascript in one hand and filter_var
with neccessary parameters and regular expression using preg_match .now as input sanitaisation has gone in a long run with so many things to keep in mind, wht to use when validating email.

for preg_match if(!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))

by javascript

function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}

by filter_var

<?php
if(!filter_var("[email protected]", FILTER_VALIDATE_EMAIL))
{
echo("E-mail is not valid");
}
else
{
echo("E-mail is valid");
}
?>
3
  • The difference is: In practice - none, in implementation - a lot. Both will validate your input but I recommend to use the same regex in both cases. Commented Dec 10, 2013 at 21:40
  • not in implementation? any other way to handle with more enhancement. thnx in adv. Commented Dec 10, 2013 at 21:45
  • I agree with Eric, you should just use the regex in both places. Commented Dec 10, 2013 at 21:50

1 Answer 1

0

Yes, those three variants are very different.

  • preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)
    

    This regex is very restrictive - actually, it's too restrictive. It does only allow word characters and minuses around the @-sign and dot. For example, it does not even allow subdomains (which are quite common).

  • var atpos = email.indexOf("@");
    var dotpos = email.lastIndexOf(".");
    return !(atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
    

    This looks quite well. It checks for the existence of an @ and a . in the correct order, which is enough to identify email-like looking strings. It could be replaced by the regular expression /.+@.+\..+/.test(email) (which would not allow linebreaks, but that's fine).

  • filter_var($email, FILTER_VALIDATE_EMAIL)
    

    This is probably the best way to do it in PHP, but notice that is has some flaws as well.

I would also recommend the article Stop Validating Email Addresses With Complicated Regular Expressions :-)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.