In this article, we will learn how to create a registration form that checks if the given Email Id is available for use or someone has already registered on that Email ID.

Check email ID availability using C#

To get started, let create the table below in an SQL Server Database

The Database

To create the table, use the SQL below:

BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Users
	(
	Id int NOT NULL IDENTITY (1, 1),
	UserName nvarchar(50) NULL,
	EmailID nvarchar(50) NULL
	)  ON [PRIMARY]
GO
ALTER TABLE dbo.Users SET (LOCK_ESCALATION = TABLE)
GO
COMMIT

The Stored Procedure

The following stored procedure will check for the Email availability for registration. It returns 1 if the Email address isn’t found in the database or return 0 if the email already exists in the database and thus is not available. This procedure takes the Email ID as a parameter.

SET ansi_nulls ON 

go 

SET quoted_identifier ON 

go 

Create PROCEDURE [dbo].[CheckemailIDavailability] @emailId NVARCHAR(50) 
AS 
  BEGIN 
      SET nocount ON; 

      IF NOT EXISTS(SELECT username 
                    FROM   users 
                    WHERE  emailid = @emailId) 
        BEGIN 
            SELECT '1' -- Email ID is available 
        END 
      ELSE 
        BEGIN 
            SELECT '0' -- Email ID not available 
        END 
  END 

go

You need to import the following namespaces:

  using System.Data;
  using System.Data.SqlClient;

The HTML

    <br />
    <div >
      
        <input id="txtEmailId" type="text" />
        <input id="btnCheck" type="button" value="Check Availability" onclick="CheckEmailAvailability()" />
 
    </div>

To use jQuery, you need to link to jQuery first.

 src="https://code.jquery.com/jquery-3.4.1.js"
  integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
  crossorigin="anonymous"></script>

The JavaScript

The JavaScript code will be as follows.

    <script type="text/javascript">
        function CheckEmailAvailability() {

            var emailId = $("#txtEmailId").val();

            $.ajax({
                type: "POST",
                async: false,
                url: 'Default.aspx/CheckEmailAvailability',
                data: '{emailId: "' + emailId + '" }',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (response) {

                    if (response.d == 1) {

                        alert('EmailID "' + emailId + '" is available!');
                    }
                    else {
                        alert('EmailID ' + emailId + ' is taken!');
 
                    }
                }
                ,
                error: function (response) {
                    alert("Error Occurs!");
                }


            });
        };
</script>

The JavaScript function CheckEmailAvailability() gets executed when the user clicks on the button. It reads the TextBox to fetch the Email address needs to be checked and then calls the code-behind functionCheckEmailAvailability, which calls the stored procedure and returns the value to the user.

The C# function

        [System.Web.Services.WebMethod]
        public static string CheckEmailAvailability(string emailId)
        {
            string result =  "";
            string constr = "Data Source=localhost;Initial Catalog=Books;Integrated Security=True";
            using (SqlConnection conn = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("CheckEmailAvailability", conn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@EmailId", emailId);
                    conn.Open();
                    result =  cmd.ExecuteScalar().ToString();
                    conn.Close();
                }
            }
            return result;
        }

Screenshot

Related Articles

Last modified: September 30, 2019

Comments

Write a Reply or Comment

Your email address will not be published.