45

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
$("#signupForm").validate({
    rules: { 
        username: {
            required: true,
            minlength: 2
        }, },
    messages: { 
        username: {
            required: "Please enter a username",
            minlength: "username at least 2 characters"
        }, 
    }.

.......

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

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 doesn't 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 separate validation groups?

11 Answers 11

47

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
    jQuery('form').validate(); 
    // 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.

0
11

Here are examples of using the jQuery Validation plugin with WebForms and emulating the concept of validation groups with it. It actually works pretty well once you smooth out a couple issues.

2
  • 1
    The link you give contains crucial information. For instance, preventing the jQuery validation to be called on every form submit is needed when you have more than one form per page.
    – Bernard
    Apr 12, 2012 at 2:37
  • 1
    In webforms there is only 1 form per page.
    – LarryBud
    Jan 18, 2017 at 13:16
11
$("#signupForm").validate({
        rules: { 
                <%= tbUsername.UniqueID %>: {
                        required: true,
                        minlength: 2
                }, },
        messages: { 
                <%= tbUsername.UniqueID %>: {
                        required: "Please enter a username",
                        minlength: "username at least 2 characters"
                }, 
        });

<asp:TextBox ID="tbUsername" runat="server"></asp:TextBox>
3
  • 1
    UniqueID solved my problem, thanks! I'm using ASP.NET 4 with Webforms.
    – brunosp86
    Feb 15, 2011 at 15:39
  • 2
    You can also use clientidmode then. set it to static in the page directive or per control ClientIDMode="Static" and refer to that like $('#tbUsername') Aug 10, 2011 at 10:18
  • Thanks man. You just helped me make sense of 8 hours' work...Appreciate! Mar 4, 2013 at 20:35
4

You can check xVal.webForms here: http://xvalwebforms.codeplex.com/

1
  • This is an awesome plugin for integrating jQuery validation with ASP.NET. Makes life so easy with support of validation groups, validation summary & ability to turn off client side validation(if required).
    – Gopinath
    Dec 22, 2011 at 8:33
2

Tested what Darin Dimitrov said and it works perfectly, but if you don't want to set a specific class to each of your fields, you can use jQuery selectors:

$('form').validate();
$('input[id$=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" />
2

The best solution is use "<%=tbUsername.UniqueID %>" instead of tbUsername in jQuery rules.

$("#signupForm").validate({
rules: { 
    "<%=tbUsername.UniqueID %>": {
        required: true,
        minlength: 2
    }, },
messages: { 
    "<%=tbUsername.UniqueID %>": {
        required: "Please enter a username",
        minlength: "username at least 2 characters"
    }, 
}.
0

I recently posted a patch file for xVal.WebForms which resolves the multiple forms issue relaying on the well known ASP.Net validation Group. This patch also supports the ASP.Net CausesValidation property.

Yo can read about it here: http://cmendible.blogspot.com/

0

A great way to do this is to use:

<%= textbox.Name %> or <%= textbox.ClientId %> whenever you need to reference a server item.

i.e.

var phoneNumb = $('#<%= tPhone.ClientID %>').val(); 

or

$("#signupForm").validate({
        rules: { 
                <%= username.Name %>: {
                        required: true,
                        minlength: 2
                }, },
        messages: { 
                <%= username.Name %>: {
                        required: "Please enter a username",
                        minlength: "username at least 2 characters"
                }, 
        }.

.......

0

For SharePoint 2010 I found with loading different usercontrols as views (via ajax) that this worked if you move javascript into a library and can't use server tags for the control id's like this:

e.g #<%= tPhone.ClientID %>

$('input[id$=tPhone]').rules('add', 
{      
 required: true,      
 messages: 
 {          
  required: 'Some custom message for the username required field'      
 }  
});

Further to this if you dynamically load a user control via Ajax then you cannot use $(document).ready You will have to encapsulate the jQuery in a function library if its on the User Control at (server side event) page load its fine but in the scenario its loaded via Ajax with the Update Panel it will not dance.

I have not tried loading usercontrols via jQuery yet, this looks heavy and appears to load the whole page albeit perhaps slightly quicker or not.

Tests comparing loading techniques showed the Update Panel was as fast and resulted in the same or smaller page sizes than other techniques and basically loaded quicker or much more data as quick or quicker.

0

I recommend using jQuery.simple.validator, its easy, lightweigh and customizable validator compatible with asp.net web forms, because basically it can perform validations in any container, not only

https://github.com/v2msoft/jquery.simple.validator

I recommend you check the plugin and the documentation. Usage:

<script type="text/javascript" src="/Content/js/jquery-plugins/jquery.simple.validator.js"></script>

<div id="container">
    <!-- REQUIRED FIELD -->
    <label>Required Field: </label><br/>
    <input type="text" id="required_field_control" data-required data-required-msg="Field is required" /><br /><br/>

    <input type="button" value="Validate" onclick='javascript:validate();' />
</div>


<script type="text/javascript">
    function validate() {
        $("#container").initialize();
        var ok = $("#container").validate();
        if (!ok)  alert("There are errors");
        else alert("Form is ok");
    }
</script
1
  • His question was about using validate with webforms.
    – LarryBud
    Jan 18, 2017 at 13:14
0

The information in this article led me to use Control.ClientID when looking for a match with jQuery... Very useful information...

<label for="<%= tbName.ClientID %>">Name</label>
<input id="cphBody_tbName" runat="server" .../>

Not the answer you're looking for? Browse other questions tagged or ask your own question.