Monday, January 17, 2011

How to validate post code in webform project by ajax in JQuery calling web service

1.       Web service (Validation.asmx):
    [System.Web.Script.Services.ScriptService]
    public class Validation : System.Web.Services.WebService
    {        public bool GetPostCodeValidation(string statename, string postcode)
        {
            if (postcode == ""return true;
            if (statename == ""return true;

            System.Text.RegularExpressions.Regex r;
            switch (statename)
            {
                case "CA":
                    r = new System.Text.RegularExpressions.Regex(@"^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$");
                    return r.IsMatch(postcode.ToUpper());
                case "US":
                    r = new System.Text.RegularExpressions.Regex(@"^(\d{5}-\d{4}|\d{5}|\d{9})$|^([a-zA-Z]\d[a-zA-Z] \d[a-zA-Z]\d)$");
                    return r.IsMatch(postcode);
                default:
                    return true;
            }
        }
    }

2. JQuery ajax call
<script type="text/javascript">

    function ValidatePostCode(source, args) {

        var pc = $("#<%=textboxPostalCode.ClientID %>").val();

        var state = $("#<%=dropdownlistProvince.ClientID %>").val();

        $.ajax({

            type: "POST",

            contentType: "application/json; charset=utf-8",

            url: '<%=ResolveClientUrl("~/Validation.asmx/GetPostCodeValidation")%>',

            data: "{'statename':'" + state + "','postcode':'" + pc + "'}",

            dataType: "json",

            async: false,

            success: function (data) {

                args.IsValid = data.d;

            }

        });

    }

</script>

Please use synchronized call


3. Add custom validator in Html view
<asp:TextBox ID="textboxPostalCode" runat="server"/>           
<asp:CustomValidator ID="customValidatorPostcode" runat="server" ControlToValidate="txtPostalCode" ClientValidationFunction="ValidatePostCode"/>

No comments:

Post a Comment