0

I have an asp.net form with a login section and a register section. There are two submit buttons that correspond to the appropriate section, login or register. I am using jquery validation, however I cannot find a way to specify validation groups as I would with normal asp.net validation. When I click the register button, right now it is asking for the login fields to be filled in. Anyone have any thoughts on this? THANKS!

6 Answers 6

5

I'm guessing you are using this validation plugin: JQuery Validation . The plugin uses the form tag as a validation group so to accomplish what you want you will need to remove rules depending on which button the user pushes. Also, you will need to add the rules back for the case where the validation fails then the user decides to click the other button.

Here's an example:

$(document).ready(function()
{
    $("#form").validate({
        invalidHandler: addRules 
    });        

    addRules();        

    $("#submit1").click(function(){
        $(".group2").each(function(){
            $(this).rules("remove");
        });
    });
    $("#submit2").click(function(){
        $(".group1").each(function(){
            $(this).rules("remove");
        });
    });

});
var addRules = function(){
    $("#input1").rules("add", {required:true});
    $("#input2").rules("add", {required:true});
}

This approach allows you to add a class attribute (group1 or group2) to each of your inputs which acts as a validation group.

2
  • if only it were that easy. In asp.net, you may only have one <form runat="server"> tag. Therefore, I need to know if there is such thing as validationgroups (which normal asp.net validation uses).
    – bmorehokie
    Oct 21, 2009 at 19:31
  • @Jataro do you know how to disable jquery validation for one submit button? I have two submit buttons on my form: Submit and Cancel. I need to disable validation for Cancel button. Feb 25, 2014 at 0:16
1

Rather than having to write page specific code to workaround this issue you could make use of the following library:

https://github.com/bbraithwaite/JQueryValidationForWebForms

NB Source code is below but the Github link will always have most recent source.

It sits on top of the jQuery Validation Framework and abstracts away this problem by making use of class names as a convention.

You register the validation event in the same way as jQuery validation (just with a different name):

$(function() {
    $("#aspForm").validateWebForm();
});

Example .ASPX

A basic .aspx example with two validation groups might look as below. You would just wrap each logical section and give it a class name of "form" and on the action that should trigger the validation event just add the class "submit":

 <fieldset class="form">
 <div class="something">
 <ul></ul>
 </div>
 <legend>Sign Up</legend>
 <p>
 <asp:Label ID="uiFirstName" runat="server" AssociatedControlID="uxFirstName" Text="First name:"></asp:Label>
 <asp:TextBox ID="uxFirstName" runat="server" CssClass="required"></asp:TextBox>
 </p>
 <p>
 <asp:Button ID="uxRegister" runat="server" Text="Sign Up" CssClass="submit signup" />
 <asp:Button ID="uxCancelRegister" runat="server" Text="Cancel" />
 </p>
 </fieldset>
 <fieldset class="form">
 <legend>Login</legend>
 <p>
 <asp:Label ID="uiUserName" runat="server" AssociatedControlID="uxUserName" Text="User name:"></asp:Label>
 <asp:TextBox ID="uxUserName" runat="server" CssClass="required email"></asp:TextBox>
 </p>
 <p>
 <asp:Button ID="uxLogin" runat="server" Text="Login" CssClass="submit login" />
 <asp:Button ID="uxCancelSignUp" runat="server" Text="Cancel" />
 </p>
 </fieldset>

Source Code

(function ($) {

    $.extend($.fn, {
        validateWebForm: function (options) {

            var form = $(this[0]),
                formExists = (form.length) && form.is('form');

            if (formExists) {
                if (!options) {
                    options = {};
                }

                // stop the validation from firing on the form submit
                options.onsubmit = false;

                // wire up the default jquery validation event to the form
                this.validate(options);

                // Select any input[type=text] elements within a validation group
                // and attach keydown handlers to all of them.
                $('.form :text').keydown(function (event) {
                    // Only execute validation if the key pressed was enter.
                    if (event.keyCode == 13) {
                        $(event.currentTarget).closest(".form").find(".submit").click();
                    }
                });

                // find the submit buttons and override the click event
                form.getSumbitControls().click(this.validateAndSubmit);

                return this;
            }

            return undefined;
        },
        getSumbitControls: function () {
            return $(this).find('.form .submit');
        },
        getValidationContainer: function (submitControl) {
            return $(submitControl).closest('.form');
        },
        validateAndSubmit: function (event) {
            // Ascend from the button that triggered this click event 
            // until we find a container element flagged with 
            // .validationGroup and store a reference to that element.
            var group = $(this).getValidationContainer(event.currentTarget),
                isValid = true;

            // Descending from that .form element, find any input
            // elements within it, iterate over them, and run validation on 
            // each of them.
            group.find(':input').each(function (i, item) {
                if (!$(item).valid()) {
                    isValid = false;
                }
            });

            // If any fields failed validation, prevent the button's click 
            // event from triggering form submission.
            if (!isValid) {
                event.preventDefault();
            }
        }
    });

})(jQuery);

Nuget Users

PM> Install-Package JQuery.Validation.WebForms

This evolved from reading the following post from Dave Ward:

http://encosia.com/asp-net-webforms-validation-groups-with-jquery-validation/

0
1

You can always use some simple jquery/javascript to remove the "validate[required]" class on the asp button OnClientClick and then add it back on the other buttons OnClientClick which is easier than changing the validationengine files or replacing them. An example of this would be:

<div id="Login">
    <asp:TextBox ID="txtUser" runat="server" CssClass="validate[required]"></asp:TextBox>
    <asp:TextBox ID="txtPass" runat="server" CssClass="validate[required]"></asp:TextBox>
    <asp:Button ID="btnLogin" runat="server" OnClientClick="disableReg();" OnClick="btnLogin_Click" />
</div>
<div id="Register">
    <asp:TextBox ID="txtName" runat="server" CssClass="validate[required]"></asp:TextBox>
    <asp:TextBox ID="txtEmail" runat="server" CssClass="validate[required]"></asp:TextBox>
    <asp:Button ID="btnReg" runat="server" OnClientClick="disableLogin();" OnClick="btnReg_Click" />
</div>

The javascript would be:

function disableReg() {
    $('#<%=txtName.ClientID%>').removeClass("validate[required]");
    $('#<%=txtEmail.ClientID%>').removeClass("validate[required]");
    $('#<%=txtUser.ClientID%>').addClass("validate[required]");
    $('#<%=txtPass.ClientID%>').addClass("validate[required]");
    return true;
}

function disableLogin() {
    $('#<%=txtUser.ClientID%>').removeClass("validate[required]");
    $('#<%=txtPass.ClientID%>').removeClass("validate[required]");
    $('#<%=txtName.ClientID%>').addClass("validate[required]");
    $('#<%=txtEmail.ClientID%>').addClass("validate[required]");
    return true;
}
0
0

Keep track of the validation object and remove/replace rules directly. Works for me with v1.13.0

var validation = $('#form1').validate(); //Keep track of validation object

//Rule set 1
var validationRulesLogin = {
    headerEmail: {
        required: true,
        email: true
    },
    headerPassword: "required"
};
var validationMessagesLogin = {
    headerEmail: {
        required: "Please enter your email address.",
        email: "Not a valid email address."
    },
    headerPassword: "Please enter your password."
};

//Rule set 2
var validationRulesSignup = {
    signupEmail: {
        required: true,
        email: true
    },
    signupPassword: "required",
    signupPassword2: {
        equalTo: "#phBody_txtNewPassword"
    }
};
var validationMessagesSignup = {
    signupEmail: {
        required: "Please enter your email address.",
        email: "Not a valid email address."
    },
    signupPassword: "Please enter your password.",
    signupPassword2: "Passwords are not the same."
};

//Toggle rule sets on form focus, button click or other event.
function validatingLoginForm(){
    validation.resetForm();
    validation.settings.rules = validationRulesLogin;
    validation.settings.messages = validationMessagesLogin;
}
function validationSignupForm(){
    validation.resetForm();
    validation.settings.rules = validationRulesSignup;
    validation.settings.messages = validationMessagesSignup;
}
-1

if you are using unobtrusive jquery validation, alternatively you could use this:

$(document).ready(function () {

    var formValidator = $("form").validate();

    $("#btnLogin").click(function () {
        formValidator.settings.ignore = "#registerSection *";
    });

    $("#btnRegister").click(function () {
        formValidator.settings.ignore = "#loginSection *";
    });
});
-2

Make the ASP.NET server validation logic available to client-side/jQuery by affixing special CSS class names onto the HTML elements representing server-side validation controls.

The CSS class names generated will represent validation groups. Therefore ,for example, some text boxes will be tagged with the class name for one validation group, and other text boxes for a different validation group.

For example, write and call this C# function in the Page PreRender handler, or before the page is rendered to imbue server controls with special CSS.

/// <summary>
/// Makes the server validation logic knowledge available to the client side
/// by appending css class names to validators and html elements being validated.
/// The generated css classes can be targeted by jQuery in the DOM.
/// </summary>
/// <param name="cssPrefixValidator">prefix string for validator css names</param>
/// <param name="cssPrefixTarget">prefix string for target element css names</param>
/// <remarks>
/// The css prefix arguments to this function help distinguish between what is a 
/// validation control and what is an html element being targeted by said validation control.
/// </remarks>
/// 
void TagValidationWithCss(string cssPrefixValidator, string cssPrefixTarget) {

    List<string> valClasses = new List<string>();
    List<string> targetClasses = new List<string>();

    // iterate over validator server controls
    foreach (BaseValidator val in Page.Validators) {

        // keep a unique list of generated validator css class names
        string classnameVal = cssPrefixValidator + val.ValidationGroup;
        if (!valClasses.Contains(classnameVal))
            valClasses.Add(classnameVal);
        // ..and mark the validator element with the generated css class name
        val.CssClass += (string.IsNullOrEmpty(val.CssClass) ? "" : " ") + classnameVal;

        // keep a unique list of generated target element css class names
        string classnameTarg = cssPrefixTarget + val.ValidationGroup;
        if (!targetClasses.Contains(classnameTarg))
            targetClasses.Add(classnameTarg);
        // ..and mark the target element with the generated css class name
        Control target = FindControl(val.ControlToValidate);
        if (target is HtmlControl)
            ((HtmlControl)target).Attributes["class"] += (string.IsNullOrEmpty(val.CssClass) ? "" : " ") + classnameTarg;
        else if (target is WebControl)
            ((WebControl)target).CssClass += (string.IsNullOrEmpty(val.CssClass) ? "" : " ") + classnameTarg;
    }

    // output client script having array of validator css names representing validation groups
    string jscriptVal = string.Format("<script>window['{1}'] = ['{0}'];</script>", string.Join("','", valClasses.ToArray()), cssPrefixValidator);
    ClientScript.RegisterStartupScript(this.GetType(), "val", jscriptVal);

    //output client script having array of html element class names representing validation groups
    string jscriptTarg = string.Format("<script>window['{1}'] = ['{0}'];</script>", string.Join("','", targetClasses.ToArray()), cssPrefixTarget);
    ClientScript.RegisterStartupScript(this.GetType(), "targ", jscriptTarg);
}

The function is called in the server-side Page:

protected override void OnPreRender(EventArgs e) {
    base.OnPreRender(e);

    TagValidationWithCss("validator-", "target-");
}

The declarative syntax of the ASPX page might have your two sections like so:

<div>

Login Section
    <asp:TextBox ValidationGroup="vg1" ID="TextBox1" runat="server"></asp:TextBox><asp:TextBox
        ValidationGroup="vg1" ID="Textbox2" runat="server"></asp:TextBox><asp:Button ID="Button1"
            ValidationGroup="vg1" runat="server" Text="Button" />
    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="TextBox1"
        ErrorMessage="RequiredFieldValidator" ValidationGroup="vg1"></asp:RequiredFieldValidator>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="Textbox2"
        ErrorMessage="RequiredFieldValidator" ValidationGroup="vg1"></asp:RequiredFieldValidator>

    <hr />

Registration Section
    <asp:TextBox ValidationGroup="vg2" ID="TextBox4" runat="server"></asp:TextBox><asp:TextBox
        ValidationGroup="vg2" ID="Textbox5" runat="server"></asp:TextBox><asp:Button ID="Button3"
            ValidationGroup="vg2" runat="server" Text="Button" />
</div>

Now over to the rendered page to see the results .....

The page HTML source contains arrays of generated CSS names representing validation groups, one set for validators (validator-) and another for targets of validation (target-)

<script>window['validator-'] = ['validator-vg1','validator-vg2'];</script>
<script>window['target-'] = ['target-vg1','target-vg2'];</script> 

These CSS names are also rendered on the html elements. Notice "target-vg1" CSS classes on text boxes here, representing validation group #1. The text boxes represent the login screen/interface on the page (one of two UI parts):

<input name="TextBox1" type="text" id="TextBox1" class=" target-vg1" /><input name="Textbox2" type="text" id="Textbox2" class=" target-vg1" /><input type="submit" name="Button1" value="Button" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;Button1&quot;, &quot;&quot;, true, &quot;vg1&quot;, &quot;&quot;, false, false))" id="Button1" /> 

This second set of textboxes is on the same ASP.NET page (in the same ASP.NET Form) and represent the user Registration screen/interface (the second UI part). Notice these textboxes are tagged with a different validation group named "target-vg2" through the css class.

 <input name="TextBox4" type="text" id="TextBox4" class=" target-vg2" /><input name="Textbox5" type="text" id="Textbox5" class=" target-vg2" /><input type="submit" name="Button3" value="Button" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;Button3&quot;, &quot;&quot;, true, &quot;vg2&quot;, &quot;&quot;, false, false))" id="Button3" /> 

So we injected special Css names into the ASP.NET flow without interrupting or breaking it.

Ultimately this specialized output allows you to write custom scripts against it (i.e. using jQuery) to grab onto those special CSS class names and to distinguish between validation groups on the client side.

This simple example alerts the names of the validation groups on the client side to prove they are seen and known. Whew!

<script>
    // Tell the CSS names of the available validation groups assigned to target elements.
    var strGroups = 'css validation groups are: ' + window['target-'].join(', ');
    alert(strGroups);
</script>

jQuery can be used to target the special css classes too.

This doesn't cover all cases. It might be really out to lunch, but was interesting to make. The server- and client-side code would need to be tweaked to personal or project taste.

(You also want to rely on the fact that newer browsers can apply multiple CSS classes to one element using the 'class' attribute by separating class names with spaces e.g - class="vg1 animated bright myclass your class". This allows the generated css class names to be appended after existing class names without overwriting them.)

1
  • 1
    Way way way too complicated. I don't want to even think about server-side code for something so simple that doesn't need to be complicated.
    – Aaron
    Jun 13, 2010 at 7:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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