Custom Validator: validation with ajax call

Hello/Namaste all,

Nowadays we do not like to work with postbacks and update panel, this is the time of Jquery/Javascript and Ajax.

So, sometimes we wanted to validate a form from javascript itself without doing postback by calling some method in code behind. So, today we will see how we can validate a form from javascript by doing ajax call to code behind. And what kind of difficulties we will face.

Starting with, we can use custom validator’s client side javascript function, Ajax call ($ajax() function), PageMethod/WebMethod to validate from javascript having actual logic in code behind PageMethod/WebMethod.

Please see below:

  Default.aspx

<form id="form1" runat="server">
        <div>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
            <asp:CustomValidator ID="cmtxtForm" runat="server" ClientValidationFunction="OnClientValidate" SetFocusOnError="true"
                ErrorMessage="Email address already exist" ValidateEmptyText="false" ValidationGroup="FormSubmit">
            </asp:CustomValidator>
            <asp:Button ID="btnSubmit" runat="server"  OnClick="btnSubmit_Click" Text="Submit" ValidationGroup="FormSubmit" />
        </div>

        <script type="text/javascript">
            function OnClientValidate(sender, args) {
                var Email = document.getElementById("txtEmail").value;
                if (Email != null && Email != "") {
                    alert(Email);
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "Default.aspx/CheckIfEmailExist",
                        data: "{'Email': '" + Email + "'}",
                        dataType: "json",
                        success: function (result) {
                            args.IsValid = result.d;
                            alert(args.IsValid);
                        }
                    });
                }
                else {
                    args.IsValid = false;
                }
                alert(args.IsValid);
            }
        </script>

Default.aspx.cs

    #region PageMethods

    [WebMethod]
    public static bool CheckIfEmailExist(string Email)
    {
        if (Email.ToLower() == "psatikunvar7@gmail.com")
            return false;
        else
            return true;
    }

    #endregion PageMethods

Note: Here, it will call web method and return the result, but if you will check by implementing above code, what you will find is inaccurate args.IsValid in both alert function. No matter what code behind function returns, IsValid will always be true.

This is because, $.ajax() method is by default async method. so, to get the actual response from the PageMethod/WebMethod in ajax function inside client side validation function for custom validator, we need to set option async to false in ajax function as shown below:

 $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "Default.aspx/CheckIfEmailExist",
        data: "{'Email': '" + Email + "'}",
        dataType: "json",
        async: false,
        success: function (result) {
            args.IsValid = result.d;
            alert(args.IsValid);
        }
 });

That’s it. Now it should work fine as per value PageMethod/WebMethod is returning.

If you enjoy working with Jquery and Ajax please drop anything you want to share about it in comment. i would like to learn and discuss.

Thank You. Stay Hungry 🙂

Advertisements

2 thoughts on “Custom Validator: validation with ajax call

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s