Please support us by disabling ad blocker for smarttutorials.net ...

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 Custom 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

Demo

 

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 Custom Methods, Ajax and PHP

Step 1:

Create sample MySQL table using following sql query.

CREATE TABLE IF NOT EXISTS `test` ( 
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

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

INSERT INTO `test` (`id`, `email`) VALUES
(1, 'muni2explore@gmail.com'),
(2, 'sasi@gmail.com');
Unique Email Validation Based on Checkbox Using jQuery Validation Plugin Custom Methods, Ajax and PHP

Download

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
define('DB_HOST', 'localhost');
define('DB_NAME', 'test');
define('DB_USER','root');
define('DB_PASSWORD','');

$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());

?>

Step 3:

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

<!DOCTYPE HTML>
<html>
<head>

<title>Unique Email Validation Based on Checkbox Using jQuery Validation Plugin Custom Methods, Ajax and PHP</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>
<script src='http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js'></script>
</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'>
	<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 type='submit' name='submit' value='submit' class='but'/>
			</td>
		 </tr>
	</table>
</form>

<p> Following Email : <span>muni2explore@gmail.com</span> is already exists in database. Enter this email in the textbox to check.</p>
</div>
</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 jQuery validation script, this script only 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.

<script>
   $('document').ready(function(){
       $("#mailForm").validate({
			     rules: {

					email:{ 
					   required: true,
					   email: true,
					   uniqueEmail: true
					}
			     },
			     messages: {

						email:{ 
						   required: "Please enter your email",
						   email: "Please enter a valid email address",
						   uniqueEmail: "Email is already exists"
						}
			     },
				debug: true,
				errorElement: "em",
				errorContainer: $("#warning, #summary"),
				errorPlacement: function(error, element) {
					error.appendTo( element.parent("td").next("td") );
				},
				success: function(label) {
					label.text("ok!").addClass("success");
				}
		});		 
   });
</script>

Step 5:

Now I am going write jQuery Validation Plugin custom method with ajax call to check email uniqueness. The script will get information about radiobox selected and email entered in the textbox and sends those information to PHP file through jQuery .ajax() method. Where it will checks against emails in the database.

jQuery.validator.addMethod("uniqueEmail", function(value, element) {
    var response;
	var email_chk;
	if ($('#email_chk').is(':checked')) {
		email_chk=$('#email_chk').val();
	}else{
	    email_chk='No';
	}

	var email=$('#email').val();
    $.ajax({
        type: "POST",
        url: "unique_email.php",
        data:{email_chk:email_chk,email:email},
        async:false,
        success:function(data){
            response = data;
        }
    });
    if(response == 'true')
    {
        return true;
    }
    else
    {
        return false;
    }

}, "Email is Already Taken");

Step 7:

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
require_once 'config.php';

$flag=$_POST['email_chk'];
$email=$_POST['email'];

if($flag=='email_chk'){
	  $query="select count(email) from user where email='$email'";
	   $response=mysql_query($query);
	   $result=mysql_fetch_array($response);
	   if($result[0]>0){
		  echo 'false';
	   }
	   else{
		 echo 'true';
	   }
}
else{
    echo 'true';
}

?>

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!