viernes, 17 de junio de 2016

How to Validate Email Address in PHP


So How to Validate Email Address in PHP?

Here I'll show you two different methods to validate email address in php. The first method is by using filter_var() function and the second one by using regex pattern.

Method 1: Using filter_var() function

This is the absolute easiest way by which you can validate an email address in php. The method uses PHP's filter_var() function which is simple and safe to check if an email id is well formed and valid. The only downside to this method is it works only with PHP >= v5.2.0.
Below is the php function to validate email address using filter_var().
<?php
function validate_email($email=NULL) {
    return (filter_var($email, FILTER_VALIDATE_EMAIL) ? "$email is a valid email-id" : "$email is an invalid email-id");
}

echo validate_email("user.example@gmail.com");
echo "<br/>" . validate_email("user.example.com");

// output
// user.example@gmail.com is a valid email-id
// user.example.com is an invalid email-id
?>

Method 2: Using Mighty RegEx

If your PHP version is less than 5.2.0, then you have to go with the (crazy) regular expression method to validate the email address. Here is the php function to check if email-id is valid or not using regular expressions.
<?php
function validate_email($email=NULL) {
    return (preg_match("/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/",$email) ? "$email is a valid email-id" : "$email is an invalid email-id");
}

echo validate_email("user.example@gmail.com");
echo "<br/>" . validate_email("user_example@yahoo");

// output
// user.example@gmail.com is a valid email-id
// user_example@yahoo is an invalid email-id
?>
By using the above two methods you can easily validate the email address in php but still using filter_var() is the best option in most of the cases.
http://www.kodingmadesimple.com/2016/06/how-to-validate-email-address-in-php.html?utm_content=buffer63221&utm_medium=social&utm_source=facebook.com&utm_campaign=buffer

No hay comentarios:

Publicar un comentario