QuizCure
Find Available Solution Here!

Ajax Email Validation in jquery

Deepak Dec 21, 2024

It is essential to validate user input email before performing actual business logic.

Email validation is required due to following reasons

  • To check whether an entered email is valid or not at the client-side using javascript/jQuery code.
  • Sanitize Email before processing to avoid illegal characters
  • Validate email from the server using ajax by sending a request to the server on LogIn/Registration form submission

Let's start learning ajax email validation in jquery with these easy steps:

jquery regex validation for email at client side

It is recommended to check user input email validity at the client-side before sending it to the server. Regular expression to check email validity at client-side :

^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$

Lets assume email address as abc1234@quizcure.com

What above RegEx pattern mean here:

  • ^ used to match the starting position of any line.
  • $ used to match the end position of any line.
  • [a-zA-Z0-9_.+-] used to match all alphanumeric characters with respected cases mentioned in bracket [] with printable characters. In our example, it matched with the first part (abc1234) of the email address
  • [a-zA-Z0-9-] used to match the second part of the email after @. It can be any alphanumeric characters and hyphen.
  • \. used to add. (dot) and escaped.
  • [a-zA-Z0-9]{2,4}: Used to match alphanumeric characters as mentioned within brackets with 2 to 4 of preceding characters only.

There is another way to rewrite the above regulate expression in the following manner

^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$

Anyways actual email validity confirm by successfully sending email to inbox. Visit Here for detail about regEx different use cases

Lets conclude the above explanation with the following example code

<script>
    $(document).ready(function () {

        function isValidEmail(email) {

            var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            return regex.test(email);
        }

        $("form").submit(function (event) {

            if (isValidEmail($("#email").val())) {
                $("#result").html("Valid Email");
            } else {
                   $("#result").html("InValid Email");
            }
            
             event.preventDefault();
        });
       
    });

</script>
   

Html form

<div id="result"> </div>
<form method="post" id="demo" >
    <input type="text" name="email" id="email" class="form-control" placeholder="Enter your Email">
    <input type="submit" value="Submit" name="submitBtn" id="submitBtn" >
</form>
 

Explanation:

  • Lets suppose we have a form with email input.
  • Checking user input email on form submit. within $("form").submit Code block will be executed once submit event triggered.
  • Function isValidEmail is used here to check whether a received email is valid or not with the help of regular expression.
  • Display response message within div (with id as result )

Jquery ajax email validation in PHP

In the previous example, we see client-side email validation but it is strongly recommended to check email on the server-side as well because client-side javascript validation can be disabled.

In this section, we will see an ajax request to the server to validate the email. So lets start.

Html Form:

	<div id="result"> </div>
<form method="post" id="demo" >
    <input type="text" name="email" id="email" class="form-control" placeholder="Enter your Email">
    <input type="submit" value="Submit" name="submitBtn" id="submitBtn" >
</form>

Explanation:

  • Created div with id as result to display validation message from client & server.
  • Cerated Form email textbox for user input.

jQuery code block:

<script>
    $(document).ready(function () {

        function isValidEmail(email) {

            var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            return regex.test(email);
        }

        $("form").submit(function (event) {

            if (isValidEmail($("#email").val())) {
                $("#result").html("Valid Email");
                
                $.ajax({
                url: './server.php', // sending ajax request to this server page
                async: false,
                type: 'post',
                dataType: "json",
                data: {
                    'email': $("#email").val()
                },
                success: function (response) {
                    $("#result").html(response.message);
                }
            });
            
            } else {
                $("#result").html("InValid Email");
            }

            
            event.preventDefault();
        });
    });

</script>
 

Here is what jQuery code means:

  • Function isValidEmail is defined to check email validity at client side. User entered email value $("#email").val() is passed to isValidEmail function.
  • Display error message in div if failed to validate email.
  • Perform an ajax request to the server by sending an email value.
  • Make async false so that it will wait for server response before processing further execution.
  • Receive JSON response (As expected from client as defined dataType: "json", ) & Display response message from the server on success in specific div

Server side code block:

<?php

if (empty($_POST['email'])) {
    $data['success'] = false;
    $data['message'] = 'Email is required.';
} else {

    $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

    $isAvailable = isEmailAvailable($email);

  
    if ( $isAvailable) {
        $data['success'] = false;
        $data['message'] = 'Email is already registered with us';
    } else {
        $data['success'] = true;
        $data['message'] = 'Email is New';
    }
}

function isEmailAvailable($email) {

    try {
        $host = 'localhost';
        $db = 'test';
        $user = 'user';
        $pwd = 'pwd';


        $conn = new PDO("mysql:host=$host; dbname=$db", $user, $pwd);

        $isEmailExistSql = "select  email  from tbl_user where email = ?";

        $stmt = $conn->prepare($isEmailExistSql);
        $stmt->execute(array($email));

        $count = $stmt->rowCount();
       
        return $count > 0 ? true: false;
        
    } catch (PDOException $e) {
        echo $e->getMessage();
    }
}

echo json_encode($data);
?>
 

Here is what the server code means:

  • Here PHP is used on the server-side for demonstration purposes. You can use any server-side language.
  • Check for empty email at the server and return success: false if empty.
  • filter_var($_POST['email'], FILTER_SANITIZE_EMAIL) used to remove illegal characters from email string.
  • function isEmailAvailable is defined to check email from a database table. PHP PDO prepared a statement used here to query the database table.
  • isEmailAvailable returns true if the database table contains a record with a given email otherwise returns false.

Was this post helpful?

Send Feedback

Connect With QuizCure


Follow Us and Stay tuned with upcoming blog posts and updates.

Contributed By

Deepak

Deepak

QC STAFF
51 Posts
  • PHP
  • JAVA
  • PYTHON
  • MYSQL
  • SEO

You May Like to Read

Scroll up