Search code examples
phpregexvalidationemailserver-side

Worldwide email validation


So iv been doing a lot of reading on the best way to validate an email address before submitting a form. Iv read in multiple areas that regular expressions shouldn't be used to validate email addresses. e.g.

http://www.regular-expressions.info/email.html

Validate email address in JavaScript?

my problem with using regular expressions is that I need to be able to allow foreign characters in emails as they could be coming from anywhere in the world and I dont know how to ensure they are allowed without spending an age setting up useless accounts to test.

Further into my reading I saw someone state that validation should be done server side (as well).

All I get in search results for server-side validation are links to regular expressions.

Iv'e also looked at simple validation using indexOf and lastIndexOf on certain characters but I don't see how that will allow all the possible domains without some crazy complex code.

So essentially my question is what are the options for sever-side validation other than again using regular expressions (if there are any other options)?

Appreciate any help!


Solution

  • In PHP you can use filter_var. Example from the docs:

    $email = filter_var('bob@example.com', FILTER_VALIDATE_EMAIL);
    

    In this case, $email will contain "bob@example.com". For an invalid email address, it will contain false.