Monday, January 17, 2011

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

1.       Web service (Validation.asmx):
    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);
                    return true;

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

    function ValidatePostCode(source, args) {

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

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


            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;





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"/>

The concept of JQuery selector is from CSS selector

Borrowing from CSS 1–3, and then adding its own, jQuery offers a powerful set of tools for matching a set of elements in a document.

CSS Selector:
CSS 2 Selector reference