views:

268

answers:

1

I am making a jQuery ajax post in a javascript function used by a asp:CustomValidator control. The web method returns a boolean. How do I convert the result make the validation script function correctly.

Client side code

<script language="javascript" type="text/javascript">
function ValidateInput(source, args) {
    if($('#MyTxtBox').val().length > 0) {
        var result;
        var webMethod = 'http://domain/webservice.asmx/ValidateInput';
        var parameters = "{'input':'" + $('#MyTxtBox').val() + "'}";

        $.ajax({
            type: "POST",
            url: webMethod,
            data: parameters,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {            
                args.IsValid = msg.d;
            }
         });
    }
    else {
        args.IsValid = false;
    }
}
</script>
<asp:TextBox ID="MyTxtBox" runat="server" />
<asp:CustomValidator ID="cvCreditCardNumber" runat="server" ClientValidationFunction="ValidateCCNumber" Display="Dynamic" 
ErrorMessage="&nbsp;Please enter valid input." />

Web service code

[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public bool ValidateInput(string input)
{
    if(input.Equal("jQuery is awesome!"))
        return true;
    else
        return false;
}
+1  A: 

Well I don't think this is going to work in the usual fashion. The AJAX request is asynchronous, and since there is only one UI thread you can't block to wait on it. The validation function provided to ASP.NET must be synchronous.

You can hack it up to work, maybe, if you can delay when validation occurs and start the AJAX request early. But in this case, I'd say just use server-side validation as what you have as client-side validation is hitting the server anyway.

Frank Schwieterman
@Frank - I went ahead and removed all the ajax functionality and replaced it with `asp:RequiredFieldValidator` control. Make my life easier...
Michael Kniskern
You can just add async: false to your $.ajax() call and it should work fine.
Lance McNearney
Synchronous AJAX? Didn't realize thats possible, its still pretty yuk. Better to do server-side validation.
Frank Schwieterman