Unique Email Validation Based on Checkbox Using jQuery Validation Plugin Custom Methods, Ajax and PHP

Posted by & filed under JQUERY, PHP.

There is sometime we have requirement like this based on the User (Premium User or Guest User) We want to check Email or Username uniqueness. This is done with the help of  jQuery Validation Plugin Remote Methods, Ajax and PHP. This tutorial is continuation of my previous tutorial on Live Username and Email Availability Checking using PHP, jQuery and Ajax.

Unique Email Validation Based on Checkbox Using jQuery Validation Plugin Custom Methods, Ajax and PHP

Unique Email Validation Based on Checkbox Using jQuery Validation Plugin Remote Method, Ajax and PHP

Step 1:

Create sample MySQL table using following sql query.

CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `username` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Now add some sample data’s in the table using following SQL Query.

INSERT INTO `user` (`id`, `username`, `email`) VALUES
(1, 'muni', 'muni@gmail.com'),
(2, 'Sasi', 'sasi@gmail.com');

Step 2:

Create config.php file to keep databse connection information in a separate file, so that we can use same file multiple times without rewriting the same information again and again.

<?php
/**
 * File config.php
 * @author muni
 * @link https://smarttutorials.net/
 */
define('DB_HOST', 'localhost');
define('DB_NAME', 'smarttut_developersguide');
define('DB_USER','xyz');
define('DB_PASSWORD','mysql');

$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
    exit();
}

Step 3:

Now create index.php file and add HTML form with radios buttons and textboxes using following html code.

<!DOCTYPE HTML>
<html>
	<head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Unique Email Validation Based on Checkbox Using jQuery Validation Plugin Custom Methods, Ajax and PHP</title>
    </head>

    <body>
        <p>Unique Email Validation Based on Checkbox Using jQuery Validation Plugin Custom Methods, Ajax and PHP</p>
        <div class='main'>
            <form id='mailForm' method='post' action='index.php' novalidate>
                <table>
                    <tr>
                        <td colspan='2'> 
                            <input type="radio" id='email_chk' name="email_chk" value="email_chk">Premium User
                            <input type="radio" id='email_no' name="email_chk" value="email_chk_no">Guest User
                        </td>
                    </tr>
                    <tr>
                        <td><input type='text' name='email' id='email' class='txt'/></td>
                        <td class="status"></td>
                    </tr>
                    <tr>
                        <td colspan='2'>
                            <input id="submit_btn" type='submit' name='submit_btn' value='submit' class='but'/>
                        </td>
                    </tr>
                </table>
            </form>

            <p> Following Email : <span>muni@gmail.com</span> is already exists in database. Enter this email in the textbox to check.</p>
        </div>
        <script src='//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>
        <script src='//cdn.jsdelivr.net/npm/jquery-validation@1.19.1/dist/jquery.validate.min.js'></script>
    </body>
</html>

Step 4:

Add the following CSS styles in the head section of the index.php file.

<style>
.error{color:red;}
body{width:100%;}
p{font-family: Lobster;font-size:35px;text-align:center;}
@font-face{font-family: Lobster;src: url('Lobster.otf');}
.main{width:500px; margin:0px auto;}
.but{width:270px;background:#00BB64;border:1px solid #00BB64;height:40px;border-radius:3px;color:white;margin-top:10px;}
.txt{width:270px;border:1px solid #00BB64;height:30px;border-radius:3px;color:#00BB64;margin-bottom:5px;}
.success{color:#00BB64;}
em.error {background:url("unchecked.gif") no-repeat 0px 0px;padding-left: 16px;color: #ff0000;font-weight: bold;}
em.success {background:url("checked.gif") no-repeat 0px 0px;padding-left: 16px;color: #33ff55 !important;}
span{color:orange;}
form{padding-left:100px;}
</style>

Step 4:

Here is the jQuery validation script, this script checks the user entered email is in the right format or not. If it is not in right format then it will asks user to enter right formatted Email.

Also checks email uniqueness using Remote method. Where remote method makes jQuery.ajax() to given url with email and selected radio box value to check to email uniqueness against in the database.

$('document').ready(function(){
    $("#mailForm").validate({
        submitHandler: function(form) {
            form.submit();
        },
        rules: {
            email:{ 
                required: true,
                email: true,
                remote: {
                    url: "unique_email.php",
                    type: "post",
                    data: {
                        email: function() {
                            return $( "#email" ).val();
                        },
                        email_chk: function(){
                            var email_chk='No';
                            if ($('#email_chk').is(':checked')) {
                                email_chk = $('#email_chk').val();
                            }
                            return email_chk;
                        }
                    }
                }
            }
        },
        messages: {
            email:{ 
                required: "Please enter your email",
                email: "Please enter a valid email address",
                remote: "Email is already exists"
            }
        },
        errorElement: "em",
        errorContainer: $("#warning, #summary"),
        errorPlacement: function(error, element) {
            element.removeClass("success");
            error.appendTo( element.parent("td").next("td") );
        },
        success: function(label) {
            label.text("ok!").addClass("success");
        }, 
        highlight: function(error, element){
            $(error).parent("td").next("td").find('em').removeClass("success");
        }
    });
});

Step 6:

Finally create unique_email.php file that will gets email entered by the user and compares this email with the emails in the database and finally returns results to the jQuery .ajax() call.

<?php
/**
 * File unique_email.php
 * @author muni
 * @link https://smarttutorials.net/
 */
require_once 'config.php';
try {
	$flag = $_POST['email_chk'];
	$email = $_POST['email'];

	if ($flag=='email_chk') {
		$stmt = $mysqli->prepare("select username, email from user where email = ?");
		if (!($stmt)) {
			throw new Exception("Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error);
		}
		$stmt->bind_param("s", $email);

		if (!$stmt->execute()) {
			throw new Exception("Execute failed: (" . $stmt->errno . ") " . $stmt->error);
		}
		
		if (!($res = $stmt->get_result())) {
			throw new Exception("Getting result set failed: (" . $stmt->errno . ") " . $stmt->error);
		}
		/* determine number of rows result set */
		$row_cnt = $res->num_rows;
		//$row_cnt = $mysqli -> affected_rows;
		if ($row_cnt >0) {
			echo 'false';
		} else {
			echo 'true';
		}
	} else{
		echo 'true';
	}
} catch (Exception $e) {
	echo 'false';
}
exit;

If Email already in the database then PHP file return false as response to jQuery .ajax() call , so jQuery won’t allows your form to submit.

Download Premium Only Scripts & 80+ Demo scripts Instantly at just 1.95 USD per month + 10% discount to all Exclusive Scripts

If you want any of my script need to be customized according to your business requirement,

Please feel free to contact me [at] muni[at]smarttutorials.net

Note: But it will be charged based on your customization requirement

Get Updates, Scripts & Other Useful Resources to your Email

Join 10,000+ Happy Subscribers on feedburner. Click to Subscribe (We don't send spam)
Every Email Subsciber could have access to download 100+ demo scripts & all future scripts.

Get Instant Script Download Access!