eiu165 eiu165 - 1 year ago 180
jQuery Question

jQuery Validation plugin in ASP.NET Web Forms

I would really like use the jQuery Validation plugin in my ASP.NET Web Forms application (not MVC). I find it easier than adding asp validators everywhere and setting the control to validate field on all of them.

I am just having some issues both when setting the class like this class="required email" which I think has something to do with having a form tag within the main form tag.

I also run into issues when calling the jquery validate using the names which become mangled in an asp control

// validate signup form on keyup and submit
rules: {
username: {
required: true,
minlength: 2
}, },
messages: {
username: {
required: "Please enter a username",
minlength: "username at least 2 characters"


<label for="username">
<input id="username" name="username" />

because this

<asp:TextBox ID="tbUsername" runat="server"></asp:TextBox>

renders as

<input name="ctl00$ContentPlaceHolder1$tbUsername" type="text" id="ctl00_ContentPlaceHolder1_tbUsername" />

and mangles the name. I can get the ClientID using
<%=tbUsername.ClientID %>
but that doesnt work with ClientName

Has anyone had any success using the jquery validator plugin with asp.net?
If so what about using multiple forms much like using seprate validation groups?

Answer Source

You can checkout the rules add function, but basically here's what you can do:

jQuery(function() {
    // You can specify some validation options here but not rules and messages
    // Add a custom class to your name mangled input and add rules like this
    jQuery('.username').rules('add', { 
        required: true, 
        messages: { 
            required: 'Some custom message for the username required field' 

<input name="ctl00$ContentPlaceHolder1$tbUsername" type="text" id="ctl00_ContentPlaceHolder1_tbUsername" class="username" />

This way no need to worry about the crappy identifiers generated by the webforms engine.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download