Email Validation with php and jquery

Generally we are using an email address to know about unique visitors, because email id is unique address of a user and to validate that email id is must for us so that our user information prevent from spammers. Email validation is possible in any scripting language and in this post we will talk about email validation with php as well as jquery. In php we can use preg_match() function to check if the email format is correct or not. We will use the follow codes:

function checkEmail($str) {
    $regex = "/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i";
    $string = trim($str);

   return preg_match($regex, $str)) ? TRUE : FALSE;
}

 

In the above codes we made a function named checkEmail() now we will implement this function to check an email address.

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

 

Now lets we talk about email validation with jquery. Now in this basic example we are checking the email instantly and getting the response. All that will possible with .keyup() jquery event. Now take a look on the codes below:

$('input[name="uemail"]').keyup(function() {

    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) ) {
        $('span.email_err').text('Email Valid!')
            .css({
                'color':'green',
                'font-weight':'bold'
             });
    }
    else {
        $('span.email_err').text('Email Not Valid!')
           .css({
               'color':'red',
               'font-weight':'bold'
           });
    }
});

 

we took an input field like :

<input size="30" name="uemail"><span class="email_err"></span>

 

On the success it will return the Email Valid! Message and on failure return Email 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.