Tuesday, 18 June 2013

Check for Duplicate Email ID using JQuery

Sometimes we need to check for duplicate EmailID or Username on Keypress. So this code will help you to check for duplicate and valid EmailID in your database.

First create teh textbox to enter the Email ID.

<asp:TextBox ID="txtEmail" runat="server" CssClass="input-text email duplicate-email txtemail"    MaxLength="100"></asp:TextBox>

Now add the following code to your header part.

<script type="text/javascript">

$(document).ready(function () {
     $('.duplicate-email').live('keypress blur', function (e) {
                if (e.keyCode === 9) {
                    emailvalidation();
                }
      });
});

 function emailvalidation() {
            SetLoader();
            var txtemail = $(".txtemail").val();
            var regemail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
            if (!regemail.test(txtemail)) {
                $('.lblmsg').text('Enter valid e-mail.');
                $(".msg_div").show();
                HideLoading();
            }
            else
                checkDupEmail(txtemail);
        }

function checkDupEmail(emailid) {
            SetLoader();
            $.ajax({
                type: "POST",
                url: "Registration.aspx/DuplicateEmailID",
                data: JSON.stringify({ EmailID: emailid }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: true,
                error: function (data) {
                    jAlert("er=" + data.d, siteTitle, '');
                    return false;
                },
                success: function (data) {
                    var status = data.d;
                    if (status == true) {
                        $('.lblmsg').text('Email Already exist.');
                        $(".msg_div").show();
                        HideLoading();
                        return false;
                    }
                    else {
                        $(".msg_div").hide();
                        HideLoading();
                        return true; ;
                    }
                }
            });
        }

</script>

Now add the webmethod tobe called by AJAX. Here DubplicateEmailID is a WebMethod. I used LINQ method I written the query in CheckDuplicateByEmailID method which will return true or false.

 [WebMethod]
        public static bool DuplicateEmailID(string EmailID)
        {
            try
            {
                UserInfoService objUserInfoService = new UserInfoService();
                bool IsExist = objUserInfoService.CheckDuplicateByEmailID(EmailID.Trim());
                return IsExist;
            }
            catch (Exception ex)
            {
                ErrHandler.WriteError(ex);
                return false;
            }
        }

No comments:

Post a Comment