Using jQuery with ASP.NET Webforms – Validation

This isn’t to be a big post on how to use everything here, but I was asked last night to help someone out with a validation requirement and they wanted to use jQuery with asp.net webforms.  Figured I’d post how I handled it.’

First, I did want to try to address the ‘mangled id’s’ – or rather the INamingContainer with it’s auto-generated IDs. (supposedly being addressed in .net 4.0 ?)

John Sheehan’s blog posted a  suitable solution to get me started:

        String.prototype.endsWith = function(str) {
            return (this.match(str + '$') == str)
        }

        jQuery.expr[":"].asp = function(a, i, m) {
            return (id = jQuery(a).attr('id')) && id.endsWith(m[3]);
        };

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

(This can go in the script tag at the top of the page)

What this does is allow us to use some custom jquery selector functionality.  An example is if I had a checkbox control:

<asp:CheckBox ID="cbTest" runat="server"  Text="Check"  />


I can use jquery to determine if it’s checked or not:

$(":asp('cbTest')").attr('checked')

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Ok, let’s get to the problem at hand:  The goal is use asp.net validators, but only fire them if the ‘cbTest’ checkbox is checked.   Additionally, when it’s checked or unchecked, it should also fire instantly to determine what should be validated.

To do this, I needed to better understand how asp.net webform validators work.  Luckily, not only did I find some information, but information with jquery on Simone Chiaretta’s blog post on ‘How to manage asp.net validation from javascript with jquery ‘

Couple of gems: there are some javascript functions we have available to us when using asp.net webforms:

ValidatorEnable is the one I’m interested in here:

ValidatorEnable($("#<%= valEncOtherMimetypeRequired.ClientID %>")[0], true);


This is good, just what I needed.  However, due to concerns with master pages, etc… I was able to use the custom selector logic instead:

ValidatorEnable($(":asp('FirstNameVal')")[0], true);
 

(note, the [0] is to to get the real DOM element and not the jQuery wrapper around it.)

That is enough to get me started then:

Simple example is we have a dropdown and a textbox.  When the checkbox is clicked, it validates.  If it’s unchecked it turns off the validation.

Here is the html:

<form id="form1" runat="server">
    <div>
        Type
        <asp:DropDownList runat="server" ID="ddl"></asp:DropDownList>
        <asp:CustomValidator runat="server" ID="rfv" ControlToValidate="ddl"
            ClientValidationFunction="RequiredDropDownCheck"
            ErrorMessage="*" />
        <asp:CheckBox ID="cbTest" runat="server" Text="Check" />
        <asp:TextBox ID="FirstName" runat="server"></asp:TextBox>
        <asp:CustomValidator runat="server" ID="FirstNameVal"
            ControlToValidate="FirstName"
            ClientValidationFunction="RequiredFirstNameCheck"
            ErrorMessage="*"
            ValidateEmptyText="True" />
        <br />
        <asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click" />
    </div>
    </form>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }


(Messy, but this is what I received minus the validators – lol)

Now, the javascript in the head tag:

<script src="jquery-1.3.2.min.js" language="javascript" type="text/javascript"></script>

    <script type="text/javascript">
        String.prototype.endsWith = function(str) {
            return (this.match(str + '$') == str)
        }

        jQuery.expr[":"].asp = function(a, i, m) {
            return (id = jQuery(a).attr('id')) && id.endsWith(m[3]);
        };

        function RequiredFirstNameCheck(sender, args) {
            if ($(":asp('cbTest')").attr('checked')) {
                if ($(":asp('FirstName')").val().length == 0) {
                    args.IsValid = false;
                    return;
                }
            }
            args.IsValid = true;
        }

        function RequiredDropDownCheck(sender, args) {
            if ($(":asp('cbTest')").attr('checked')) {
                if ($(":asp('ddl')").val() == 0) {
                    args.IsValid = false;
                    return;
                }
            }
            args.IsValid = true;
        }

        $(function() {
            $(":asp('cbTest')").click(function() {
                if ($(":asp('cbTest')").attr('checked')) {
                    ValidatorEnable($(":asp('FirstNameVal')")[0], true);
                    ValidatorEnable($(":asp('rfv')")[0], true);
                }
                else {
                    ValidatorEnable($(":asp('FirstNameVal')")[0], false);
                    ValidatorEnable($(":asp('rfv')")[0], false);
                }
            });
        });

    </script>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

Just as a reference, I initially had “$(":asp(‘cbTest’)").change(function() {“, but IE didn’t recognize it, so I had to use the click event instead.  Not really ideal, but what can I say.

I’m sure there might be better ways to handle this, but it was interesting to see jQuery working with asp.net validators!

( More information on jQuery selectors: http://docs.jquery.com/Selectors and asp.net validation controls: http://www.codeproject.com/KB/validation/aspnetvalidation.aspx )

Advertisements

4 thoughts on “Using jQuery with ASP.NET Webforms – Validation

  1. An alternative to what you’ve done to compensate for the asp.net name mangling is to use jQuery as follows:

    $(“input[id$=cbTest]”).attr(‘checked’)

    This finds any input element with an ID that ends with cbTest.

    Best of luck to you

  2. Thanks David.

    I actually used that plugin as well on my asp.net mvc application – it worked perfectly.

    I haven’t used jquery much with webforms, mostly just mvc (which is a perfect match)!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s