Email Validation with php and jquery

Generally, we use an email address to know about unique visitors because email id is the unique address of a user. It is a must job to validate the user through its email address to make the users unique. Email validation is possible in any scripting language and in this post, we are going to talk about email validation with PHP and we will use the jQuery for the async task.

Table of content

The very first step is to check if the email address is correct or not. We could use the Regex or filter_var() function.

Email Validation with Regex

We can use the preg_match() function and a set of regex rules to identify the email.

function checkEmail($email) {
    $regex = "/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i";
    return preg_match($regex, $email) ? TRUE : FALSE;
}

Email Validation with filter_var()

Alternatively, we could use the filter_var() function which is pretty simple to use.

function checkEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL);
}

Now we have our own function to validate the email address. And we could use our function like the below codes.

if(!checkEmail($email)) {
    echo "Email not valid!";
}

Email Validation with jQuery

jQuery is a javascript library and widely used for animation, form validation, etc. with the frontend.

The next step is to validate the email address with jQuery. We can validate the email address with instant action without reloading the page. jQuery has a function .keyup() which is trigger when we press the keys from the keyboard.

Now take a look at the codes below:

$('input[name="email"]').keyup(function(e) {
    var emailStr = $(this).val();
    var regex = /^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i;

    if( regex.test(emailStr) ) {
        // Email address is valid
    }
    else {
        // Email address is not valid
    }
});

Posted by Jogesh Sharma

Jogesh Sharma is a web developer and blogger who loves all the things design and the technology, He love all the things having to do with PHP, WordPress, Joomla, Magento, Durpal, Codeigniter, jQuery, HTML5 etc. He is the author of this blog.