This is a simple example that will allow you to throw an error if the email address provided to you is invalid.
Of course you would probably getting your email address from POST/GET data but you get the point.
So, the question becomes, how do we validate for both of these situations? We can hand filter_var a callback to validate a given parameter. If you are validating the users email address through a confirmation link emailed to them, you don’t need to go through the trouble of custom callback.
Now as I said before there are a few downfalls that you might run into depending on what exactly your app needs as far as validation. If you run the code above you will notice the the email address ‘[email protected]’ is considered valid. Technically, I can have a system on my network with the name ‘email’ that has a mail server on it.
So I could in theory send an email to ‘[email protected]’ and have it delivered.
One of the questions I get asked quite a bit is how to validate an email address.
Around the web I’ve seen a number of 2 mile long regex’s and convoluted functions that ‘help’ with email validation, but they aren’t really needed.
Most of the time in your own development this will not be the case. Before we do this, though, lets look at one more example…
filter_var/filter_input The filter_var/filter_input functions are life savers when it comes to data validation, and once you know how to use them and what constants to use its pretty simple as well.
Lets look at a simple example of validating an email address.