0

I would like to validate a gridview column when inserting to prevent duplicates. The grid has paging so I have to go to the database to check all of the values in this field. Upon return, if the value exists, I would like to set the Error message to 'UserID exists'.

My problem is when the WebMethod returns with the results, I do not have access to the parameters, sender or args. The value is null when I set an alert in the success function.

Is this the best way to validate for duplicates when you have to go back to the database? If so, how can I save the sender and args parameters so the custom validation is triggered.

This is my markup:

<div id="UsersGridWrapper" runat="server">  
 <asp:UpdatePanel ID="UpdatePanelUserData" runat="server">
 <ContentTemplate>
 <asp:GridView ID="UserInfoGridView" runat="server" AllowPaging="True" PageSize="15">
    <Columns>
        <asp:TemplateField HeaderText="UserID">
            <HeaderTemplate> UserID
                 <asp:ImageButton ID="senigvUserIDFilter" runat="server" ImageUrl="Images/filter.png" OnClientClick="return ShowHideFilterTxtBox('senigvTxtUserIDFilter')" />
                <asp:TextBox ID="senigvTxtUserIDFilter" runat="server" AutoPostBack="true" style="display:none;" ClientIDMode="Static" OnTextChanged="senigvGridFilter_TextChanged">
                </asp:TextBox>
            </HeaderTemplate>
            <ItemTemplate>
                <asp:Label ID="senigvLblUserID" runat="server" Text='<%# Bind("UserID") %>' ></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>   
                <asp:Label ID="senigvLblEditUserID" runat="server" Text='<%# Bind("UserID") %>' ></asp:Label>                
            </EditItemTemplate>
             <FooterTemplate>
                <asp:TextBox ID="senigvTxtBxInsertUserID" runat="server" Text='<%# Bind("UserID") %>' ClientIDMode="Static"></asp:TextBox>      
                <asp:RequiredFieldValidator ID="senigvRequiredFieldInsertUserID" ControlToValidate="senigvTxtBxInsertUserID" runat="server"
                    ErrorMessage="Required field." ValidationGroup="InsertSenderValidation" Display="Dynamic" CssClass="message-error">
                </asp:RequiredFieldValidator>            
                    <asp:RegularExpressionValidator ID="senigvMaxValInsertUserID" ControlToValidate="senigvTxtBxInsertUserID" runat="server"
                    ErrorMessage="Maximumn length is 40." ValidationGroup="InsertSenderValidation" Display="Dynamic" CssClass="message-error"
                    ValidationExpression="^.{1,40}$" >
                </asp:RegularExpressionValidator>
                <asp:CustomValidator ID="senigvCustomInsertUserID" ControlToValidate="senigvTxtBxInsertUserID" runat="server" 
                    ValidationGroup="InsertSenderValidation" Display="Dynamic" CssClass="message-error"
                    ErrorMessage="*" ClientValidationFunction="ValidateUserID" EnableClientScript="true">
                </asp:CustomValidator>
             </FooterTemplate>
        </asp:TemplateField>          
    </Columns>     
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>

This is the jquery function that is called during custom validation:

function ValidateUserID(sender, args) {
var EnteredUserID = args.Value;
//Call to database to check if UserID exists
$.ajax({
    type: "POST",
    url: "EditUsers.aspx/DoesUserIDExist",
    data: JSON.stringify({ strUserID: EnteredUserID }),
    contentType: "application/json; charset=utf-8",
    datatype: "json",
    success: function (data, sender, args) {
        if (data.d == true) {
            args.IsValid = false;
            sender.innerHTML = "UserID exists.";
        }
        else {
            args.IsValid = true;
            sender.innerHTML = "";
        }
        return;
    },
    error: function (exception, sender, args) {
        args.IsValid = false;
        sender.innerHTML = "";
        $("#senigvTxtBxInsertUserID").val("");
        alert('An error occurred while calculating the message length: ' + exception.toString());
    }
});
};

The C# method that is called from jquery function to validate existence of UserID:

[System.Web.Services.WebMethod]
public static bool DoesUserIDExist(string strUserID)
{
    bool tbUserIDExist = false;

    PagingService.PagingClient tpagingClient = new PagingService.PagingClient();
    string tstrXmlTableData = tpagingClient.CheckUserID(strUserID);
    DataTable tdtUserID = CommonMethods.ParseXML(tstrXmlTableData);
    if ((tdtUserID != null) && (tdtUserID.Rows.Count > 0))
    {
        string tstrUserID = tdtUserID.Rows[0]["UserID"].ToString();
        if (!string.IsNullOrEmpty(tstrUserID))
        {
            tbUserIDExist = true;
        }
    }
    return tbUserIDExist;
}

The jquery function is called and correctly determines if the UserID exists in the database or not.

My problem is that in the success function, the sender object is null. How can I save this before I go to the database? Or is there a better approach to check for existence?

Gloria Santin
  • 2,066
  • 3
  • 51
  • 124
  • have a look at this : http://stackoverflow.com/questions/3636228/asp-net-custom-validator-how-to-get-the-controltovalidate-property-on-clientv – Zaki Mar 22 '16 at 17:00
  • that is not my problem. I can identify the sender before I make the .ajax call. When it comes back from the server, `sender` and `args` are null. I tried saving the `sender and `args` objects in a variable before the ajax call so in the success function, i can set the `IsValid` and `innerHTML` attributes but that does not work either. – Gloria Santin Mar 22 '16 at 17:46

1 Answers1

0

I got this to work. In case anyone else needs to do client validation and make a database call to the server.. 1. Added a variable to the function to save the results of the server call method 2. Used the variable to set the args.IsValid function. 3. Did not need to set the innerHTML. Set the error message in the markup. It is displayed if isValid is false. Final Markup:

<asp:CustomValidator ID="senigvCustomInsertUserID" ControlToValidate="senigvTxtBxInsertUserID" runat="server" 
                        ValidationGroup="InsertSenderValidation" Display="Dynamic" CssClass="message-error"
                        ErrorMessage="UserID exists." ClientValidationFunction="ValidateUserID"  ValidateEmptyText="false" EnableClientScript="true">
</asp:CustomValidator>

Final jquery function:

function ValidateUserID(sender, args) {
        var EnteredUserID = args.Value;
        var isValid;

        //Call to database to check if UserID exists
        $.ajax({
            async: false,
            type: "POST",
            url: "EditUsers.aspx/DoesUserIDExist",
            data: JSON.stringify({ strUserID: EnteredUserID }),
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            success: function (data) {
                isValid = data.d;
            },
            error: function (exception) {
                $("#senigvTxtBxInsertUserID").val("");
                alert('An error occurred while calculating the message length: ' + exception.toString());
            }
        });
        args.IsValid = isValid;
    };

Server Method call remained the same. The boolean returned if valid was set to true; if not valid set to false.

Gloria Santin
  • 2,066
  • 3
  • 51
  • 124