Search code examples
c#asp.netpostbackclient-side-validationcustomvalidator

Asp.Net CustomValidator still invalid after ClientValidationFunction


I have a ListView whose template has a LinkButton with a CustomValidator.

<ItemTemplate>
    <div>
        <asp:LinkButton runat="server" ID="_linkButtonDelete" 
            ValidationGroup='<%# DataBinder.Eval(Container.DataItem. "Id") %>'
            CausesValidation="true" />
        <asp:CustomValidator runat="server" ClientValidationFunction="validateDelete"
            ValidationGroup='<%# DataBinder.Eval(Container.DataItem. "Id") %>'
            data-itemId='<%# DataBinder.Eval(Container.DataItem. "Id") %>'>*</asp:CustomValidator>
    </div>
</ItemTemplate>

In validateDelete function I perform a synchronous AJAX request to determine whether the specific item can be deleted.

function validateDelete(sender, args){
    var itemId = sender.dataset.itemid;
    $.ajax({
        async:false
        // other settings omitted
        success: function(jsonResult){
            args.IsValid = jsonResult.CanDelete;
        }
    });
}

However, when I click on a button for which validateDelete function sets args.IsValid = true (I checked the response with Fiddler and by debugging the function) the link does not trigger a postback and the validator is invalid (i.e. I can see the red * near the button).

Why does the validator remain invalid?


Solution

  • Thanks to hints from @Șhȇkhaṝ and @am1r_5h and the suggests from here, namely

    setting args.IsValid at the end of the code

    I was able to perform validation on client by refactoring the validateDelete function into this:

    function validateDelete(sender, args){
        var itemId = sender.dataset.itemid;
        var isValid; // <- declare outer scope variable to hold the result
        $.ajax({
            async:false
            // other settings omitted
            success: function(jsonResult){
            isValid = jsonResult.CanDelete; // <- set the result of ajax call
        }
        // Set args.IsValid at the end of the function.
        args.IsValid = isValid;
    });
    
    }